Given a binary tree, print the root to the leaf path, but add "_" to indicate the relative position.
Example:
Input : Root of below tree
A
/ \
B C
/ \ / \
D E F G
Output : All root to leaf paths
_ _ A
_ B
D
_ A
B
_ E
A
_ C
F
A
_ C
_ _ G
Asked In: Google Interview
The idea base on print path in vertical order.
👁 vertical_order
Below is complete algorithm :
- We do Preorder traversal of the given Binary Tree. While traversing the tree, we can recursively calculate horizontal distances or HDs. We initially pass the horizontal distance as 0 for root. For left subtree, we pass the Horizontal Distance as Horizontal distance of root minus 1. For right subtree, we pass the Horizontal Distance as Horizontal Distance of root plus 1. For every HD value, we maintain a list of nodes in a vector (" that will store information of current node horizontal distance and key value of root ").we also maintain the order of node (order in which they appear in path from root to leaf). for maintaining the order,here we used vector.
- While we reach to leaf node during traverse we print that path with underscore "_"
Print_Path_with_underscore function
👁 print_path
- First find the minimum Horizontal distance of the current path.
- After that we traverse current path
- First Print number of underscore "_" : abs (current_node_HD - minimum-HD)
- Print current node value.
We do this process for all root to leaf path
Below is the implementation of the above idea.
Output_ _ A
_ B
D
==============================
_ A
B
_ E
==============================
A
_ C
F
==============================
A
_ C
_ _ G
==============================
Time Complexity: O(NH2), where N is the number of nodes and H is the height of the tree..
Space Complexity: O(lMAX_PATH_SIZE)