Given a binary tree with distinct nodes(no two nodes have the same have data values). The problem is to print the path from root to a given node x. If node x is not present then print “No Path”.
Input : 1 / 2 3 / / 4 5 6 7 x = 5 Output : 1->2->5
Approach: Create a recursive function that traverses the different path in the binary tree to find the required node x. If node x is present then it returns true and accumulates the path nodes in some array arr. Else it returns false.
Following are the cases during the traversal:
- If root = NULL, return false.
- push the root’s data into arr.
- if root’s data = x, return true.
- if node x is present in root’s left or right subtree, return true.
- Else remove root’s data value from arr and return false.
This recursive function can be accessed from other function to check whether node x is present or not and if it is present, then the path nodes can be accessed from arr. You can define arr globally or pass its reference to the recursive function.
Time complexity: O(n) in worst case, where n is the number of nodes in the binary tree.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.