|
| 1 | +# Print Nodes in Bottom View of Binary Tree |
| 2 | +from collections import deque |
| 3 | + |
| 4 | + |
| 5 | +class Node: |
| 6 | + def __init__(self, data): |
| 7 | + self.data = data |
| 8 | + self.left = None |
| 9 | + self.right = None |
| 10 | + |
| 11 | + |
| 12 | +def bottom_view(root): |
| 13 | + if root is None: |
| 14 | + return |
| 15 | + |
| 16 | + # make an empty queue for BFS |
| 17 | + q = deque() |
| 18 | + |
| 19 | + # dict to store bottom view keys |
| 20 | + bottomview = {} |
| 21 | + |
| 22 | + # append root in the queue with horizontal distance as 0 |
| 23 | + q.append((root, 0)) |
| 24 | + |
| 25 | + while q: |
| 26 | + # get the element and horizontal distance |
| 27 | + elem, hd = q.popleft() |
| 28 | + |
| 29 | + # update the last seen hd element |
| 30 | + bottomview[hd] = elem.data |
| 31 | + |
| 32 | + # add left and right child in the queue with hd - 1 and hd + 1 |
| 33 | + if elem.left is not None: |
| 34 | + q.append((elem.left, hd - 1)) |
| 35 | + if elem.right is not None: |
| 36 | + q.append((elem.right, hd + 1)) |
| 37 | + |
| 38 | + # return the bottomview |
| 39 | + return bottomview |
| 40 | + |
| 41 | + |
| 42 | +if __name__ == '__main__': |
| 43 | + root = Node(20) |
| 44 | + root.left = Node(8) |
| 45 | + root.right = Node(22) |
| 46 | + root.left.left = Node(5) |
| 47 | + root.left.right = Node(3) |
| 48 | + root.right.left = Node(4) |
| 49 | + root.right.right = Node(25) |
| 50 | + root.left.right.left = Node(10) |
| 51 | + root.left.right.right = Node(14) |
| 52 | + |
| 53 | + bottomview = bottom_view(root) |
| 54 | + |
| 55 | + for i in sorted(bottomview): |
| 56 | + print(bottomview[i], end=' ') |
0 commit comments