Given a binary tree, print the root to the leaf path, but add “_” to indicate the relative position.
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.
Below is complete algorithm :
1) 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.
2) While we reach to leaf node during traverse we print that path with underscore “_”
……a) First find the minimum Horizontal distance of the current path.
……b) 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 C++ implementations of above idea.
_ _ A _ B D ============================== _ A B _ E ============================== A _ C F ============================== A _ C _ _ G
This article is contributed by Nishant Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Program to count leaf nodes in a binary tree
- Root to leaf path sum equal to a given number
- Given a binary tree, print all root-to-leaf paths
- Print nodes at k distance from root
- Print BST keys in the given range
- Print Ancestors of a given node in Binary Tree
- Find the maximum sum leaf to root path in a Binary Tree
- Print Postorder traversal from given Inorder and Preorder traversals
- Find depth of the deepest odd level leaf node
- Print Left View of a Binary Tree
- Deepest left leaf node in a binary tree
- Sum of all the numbers that are formed from root to leaf paths
- Print all nodes that don't have sibling
- Print all nodes that are at distance k from a leaf node
Improved By : ManasChhabra2