⬅ Previous Topic
Top View of a Binary TreeNext Topic ⮕
Zigzag Traversal of a Binary Tree⬅ Previous Topic
Top View of a Binary TreeNext Topic ⮕
Zigzag Traversal of a Binary Treequeue
and enqueue the root node along with its horizontal distance (hd = 0
).hdMap
) to store the latest node value at each horizontal distance.hdMap[hd]
with the node's value (this ensures the bottom-most node at that hd is recorded).hd - 1
; if it has a right child, enqueue it with hd + 1
.hdMap
and record their corresponding values. The ordered values form the bottom view of the binary tree.class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
from collections import deque
def bottomView(root):
if not root:
return []
q = deque([(root, 0)])
hdMap = {}
while q:
node, hd = q.popleft()
hdMap[hd] = node.val
if node.left:
q.append((node.left, hd - 1))
if node.right:
q.append((node.right, hd + 1))
result = [hdMap[hd] for hd in sorted(hdMap)]
return result
if __name__ == '__main__':
# Construct binary tree:
# 20
# / \
# 8 22
# / \ \
# 5 3 25
# / \
# 10 14
root = TreeNode(20,
TreeNode(8, TreeNode(5), TreeNode(3, TreeNode(10), TreeNode(14))),
TreeNode(22, None, TreeNode(25)))
print(bottomView(root))
⬅ Previous Topic
Top View of a Binary TreeNext Topic ⮕
Zigzag Traversal 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.