이진 트리가 있다고 가정하고 트리의 상위 뷰를 찾아야 하며 왼쪽에서 오른쪽으로 정렬됩니다.
따라서 입력이 이미지와 같으면 출력은 [3, 5, 8, 6, 9]가 됩니다. 3은 2보다 크고 5는 7보다 높으므로 보이지 않습니다.
이 문제를 해결하기 위해 다음 단계를 따릅니다. −
-
보기 :=새로운 빈 지도
-
q :=이중 종료 큐
-
q의 끝에 쌍(루트, 0) 삽입
-
시작 :=inf, 끝 :=-inf
-
q가 비어 있지 않은 동안 수행
-
(노드, 좌표) :=q의 왼쪽 요소, q의 왼쪽 요소 제거
-
시작 :=시작 및 좌표의 최소값
-
end :=끝과 좌표의 최대값
-
좌표가 보이지 않으면
-
view[coord] :=노드의 값
-
-
노드의 왼쪽이 null이 아니면
-
q의 끝에 삽입(노드의 왼쪽, 좌표 - 1)
-
-
노드의 오른쪽이 null이 아니면
-
q의 끝에 (노드의 오른쪽, 좌표 + 1) 삽입
-
-
-
res :=새 목록
-
범위 내에서 시작부터 끝까지 수행하려면
-
내가 보기에 있다면
-
res
끝에 view[i] 삽입
-
-
-
반환 해상도
이해를 돕기 위해 다음 구현을 살펴보겠습니다. −
예
from collections import deque
class TreeNode:
def __init__(self, data, left = None, right = None):
self.val = data
self.left = left
self.right = right
class Solution:
def solve(self, root):
view = {}
q = deque()
q.append((root, 0))
start = float("inf")
end = float("-inf")
while q:
node, coord = q.popleft()
start = min(start, coord)
end = max(end, coord)
if coord not in view:
view[coord] = node.val
if node.left:
q.append((node.left, coord - 1))
if node.right:
q.append((node.right, coord + 1))
res = []
for i in range(start, end + 1):
if i in view:
res.append(view[i])
return res
ob = Solution()
root = TreeNode(5)
root.left = TreeNode(3)
root.right = TreeNode(8)
root.right.left = TreeNode(7)
root.right.right = TreeNode(6)
root.right.left.left = TreeNode(2)
root.right.right.right = TreeNode(9)
print(ob.solve(root)) 입력
root = TreeNode(5) root.left = TreeNode(3) root.right = TreeNode(8) root.right.left = TreeNode(7) root.right.right = TreeNode(6) root.right.left.left = TreeNode(2) root.right.right.right = TreeNode(9)
출력
[3, 5, 8, 6, 9]