⬅ Previous Topic
Right View of a Binary TreeNext Topic ⮕
Bottom View of a Binary Tree⬅ Previous Topic
Right View of a Binary TreeNext Topic ⮕
Bottom View of a Binary Treequeue
and enqueue a tuple containing the root node and its horizontal distance (0).node
, hd
).hd
is not present in the map, record the node's value for that hd
.hd - 1
and the right child with hd + 1
(if they exist).class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def topView(root):
if not root:
return []
from collections import deque
queue = deque([(root, 0)])
hd_map = {}
while queue:
node, hd = queue.popleft()
if hd not in hd_map:
hd_map[hd] = node.val
if node.left:
queue.append((node.left, hd - 1))
if node.right:
queue.append((node.right, hd + 1))
return [hd_map[hd] for hd in sorted(hd_map)]
# Example usage:
if __name__ == '__main__':
# Construct binary tree:
# 1
# / \
# 2 3
# / \ \
# 4 5 6
root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3, None, TreeNode(6)))
print(topView(root))
⬅ Previous Topic
Right View of a Binary TreeNext Topic ⮕
Bottom View of a Binary TreeYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.