Bottom-left to upward-right Traversal in a Binary Tree
Input: Below is the given Tree:
Output: 2 7 2 5 6 5 11 4 9
Level 1: 2 7 2 (going upwards from bottom left to right to root)
Level 2: 5 6 5 (right from each node in layer 1/or bottom left to upwards right in this layer)
Level 3: 11 4 9 (right from each node in layer 2/or bottom left to upwards right in this layer)
Input: 1 2 3 4 5 6 7
Output: 4 2 1 5 6 3 2
Layer 1: 4 2 1 (going upwards from bottom left to right to root)
Layer 2: 5 6 3 (right from each node in layer 1/or bottom left to upwards right in this layer)
Layer 3: 2 (right from each node in layer 2/or bottom left to upwards right in this layer)
Approach: The idea is to use the Breadth-First Search technique. Follow the steps needed to solve this problem:
- Initialize a layer in a binary tree. It is a list of nodes starting from the bottom-left most node next to the previous layer and ends with the upper-right most node next to the previous layer.
- Create a stack to stores all nodes in every layer.
- Initialize a queue to maintain “roots” in each layer, a root in a layer is a node from which one may go downwards using left children only.
- Push the root node of the first layer (the tree root) in the queue.
- Define an indicator (say lyr_root) a node expected at the end of a layer which is the current layer head, a layer head is the first node in a layer.
- Traverse until the queue is nonempty and do the following:
- Get a layer root from the front of the queue
- If this layer root is the layer head of a new layer, then, pop every element in the stack i.e., of the previous layer element, and print it.
- Traverse the layer from the upper-right to the bottom-left and for each element, if it has a right child, then check if the traversed node is the layer head or not. If found to be true then, change the expected indicator to indicate to the next layer head.
- Push the right child to the root in the queue.
- Push the traversed node in the stack.
- After traversing all the layers, the final layer may still be in the stack, so we need to pop every element from it and print it.
Below is the implementation of the above approach:
2 7 2 5 6 5 11 4 9
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.