VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-path-root-given-node-binary-tree/

⇱ Print path from root to a given node in a binary tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print path from root to a given node in a binary tree

Last Updated : 13 Dec, 2023

Given a binary tree with distinct nodes(no two nodes have the same 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".

Examples:

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: 

  1. If root = NULL, return false.
  2. push the root's data into arr[].
  3. if root's data = x, return true.
  4. if node x is present in root's left or right subtree, return true.
  5. 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. 

Implementation:


Output
1->2->5

Time complexity: O(n) where n is the number of nodes in the binary tree.
Auxiliary Space: O(H) where H = height of the binary tree.

Another Approach(Iterative Approach Using Stack):

Follow the below steps to solve the above problem:

1) Start at the root node and push it onto a stack.
2) Create a separate stack to store the path from the root to the current node.
3) While the stack is not empty, do the following:
   a) Pop the top node from the stack and add it to the path stack.
   b) If the current node is the target node, print the nodes in the path stack to get the path from the root to the target node.
   c) Push the right child of the current node onto the stack if it exists.
   d) Push the left child of the current node onto the stack if it exists.

Below is the implementation of above approach:


Output
1->2->5

Time Complexity: O(N), where N is the number of nodes in given binary tree.

Auxiliary Space: O(H), where H is the height of the binary tree.

Comment
Article Tags:
Article Tags: