jmportilla / Python-for-Algorithms--Data-Structures--and-Interviews

Files for Udemy Course on Algorithms and Data Structures
2.54k stars 2.37k forks source link

Iterative Boundary Traversal of Complete Binary tree #22

Closed mohd-mehraj closed 1 year ago

mohd-mehraj commented 4 years ago

Approach:

Traverse left-most nodes of the tree from top to down. (Left boundary) Traverse bottom-most level of the tree from left to right. (Leaf nodes) Traverse right-most nodes of the tree from bottom to up. (Right boundary) We can traverse the left boundary quite easily with the help of a while loop that checks when the node doesn’t have any left child. Similarly, we can traverse the right boundary quite easily with the help of a while loop that checks when the node doesn’t have any right child.

The main challenge here is to traverse the last level of the tree in left to right order. To traverse level-wise there is BFS and order of left to right can be taken care of by pushing left nodes in the queue first. So the only thing left now is to make sure it is the last level. Just check whether the node has any child and only include them. We will have to take special care of the corner case that same nodes are not traversed again. In the example above 40 is a part of the left boundary as well as leaf nodes. Similarly, 20 is a part of the right boundary as well as leaf nodes. So we will have to traverse only till the second last node of both the boundaries in that case. Also keep in mind we should not traverse the root again.