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:
- 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.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *left, *right;
};
struct Node* getNode( int data)
{
struct Node *newNode = new Node;
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
bool hasPath(Node *root, vector< int >& arr, int x)
{
if (!root)
return false ;
arr.push_back(root->data);
if (root->data == x)
return true ;
if (hasPath(root->left, arr, x) ||
hasPath(root->right, arr, x))
return true ;
arr.pop_back();
return false ;
}
void printPath(Node *root, int x)
{
vector< int > arr;
if (hasPath(root, arr, x))
{
for ( int i=0; i<arr.size()-1; i++)
cout << arr[i] << "->" ;
cout << arr[arr.size() - 1];
}
else
cout << "No Path" ;
}
int main()
{
struct Node *root = getNode(1);
root->left = getNode(2);
root->right = getNode(3);
root->left->left = getNode(4);
root->left->right = getNode(5);
root->right->left = getNode(6);
root->right->right = getNode(7);
int x = 5;
printPath(root, x);
return 0;
}
|
Java
import java.util.ArrayList;
public class PrintPath {
public static boolean hasPath(Node root, ArrayList<Integer> arr, int x)
{
if (root== null )
return false ;
arr.add(root.data);
if (root.data == x)
return true ;
if (hasPath(root.left, arr, x) ||
hasPath(root.right, arr, x))
return true ;
arr.remove(arr.size()- 1 );
return false ;
}
public static void printPath(Node root, int x)
{
ArrayList<Integer> arr= new ArrayList<>();
if (hasPath(root, arr, x))
{
for ( int i= 0 ; i<arr.size()- 1 ; i++)
System.out.print(arr.get(i)+ "->" );
System.out.print(arr.get(arr.size() - 1 ));
}
else
System.out.print( "No Path" );
}
public static void main(String args[]) {
Node root= new Node( 1 );
root.left = new Node( 2 );
root.right = new Node( 3 );
root.left.left = new Node( 4 );
root.left.right = new Node( 5 );
root.right.left = new Node( 6 );
root.right.right = new Node( 7 );
int x= 5 ;
printPath(root, x);
}
}
class Node
{
int data;
Node left, right;
Node( int data)
{
this .data=data;
left=right= null ;
}
};
|
Python3
class getNode:
def __init__( self , data):
self .data = data
self .left = self .right = None
def hasPath(root, arr, x):
if ( not root):
return False
arr.append(root.data)
if (root.data = = x):
return True
if (hasPath(root.left, arr, x) or
hasPath(root.right, arr, x)):
return True
arr.pop( - 1 )
return False
def printPath(root, x):
arr = []
if (hasPath(root, arr, x)):
for i in range ( len (arr) - 1 ):
print (arr[i], end = "->" )
print (arr[ len (arr) - 1 ])
else :
print ( "No Path" )
if __name__ = = '__main__' :
root = getNode( 1 )
root.left = getNode( 2 )
root.right = getNode( 3 )
root.left.left = getNode( 4 )
root.left.right = getNode( 5 )
root.right.left = getNode( 6 )
root.right.right = getNode( 7 )
x = 5
printPath(root, x)
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
class PrintPath
{
public class Node
{
public int data;
public Node left, right;
public Node( int data)
{
this .data = data;
left = right = null ;
}
}
public static Boolean hasPath(Node root,
List< int > arr, int x)
{
if (root == null )
return false ;
arr.Add(root.data);
if (root.data == x)
return true ;
if (hasPath(root.left, arr, x) ||
hasPath(root.right, arr, x))
return true ;
arr.RemoveAt(arr.Count - 1);
return false ;
}
public static void printPath(Node root, int x)
{
List< int > arr = new List< int >();
if (hasPath(root, arr, x))
{
for ( int i = 0; i < arr.Count - 1; i++)
Console.Write(arr[i]+ "->" );
Console.Write(arr[arr.Count - 1]);
}
else
Console.Write( "No Path" );
}
public static void Main(String []args)
{
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
int x=5;
printPath(root, x);
}
}
|
Javascript
<script>
class Node
{
constructor(data)
{
this .left = null ;
this .right = null ;
this .data = data;
}
}
function hasPath(root, arr, x)
{
if (root == null )
return false ;
arr.push(root.data);
if (root.data == x)
return true ;
if (hasPath(root.left, arr, x) ||
hasPath(root.right, arr, x))
return true ;
arr.pop();
return false ;
}
function printPath(root, x)
{
let arr = [];
if (hasPath(root, arr, x))
{
for (let i = 0; i < arr.length - 1; i++)
document.write(arr[i] + "->" );
document.write(arr[arr.length - 1]);
}
else
document.write( "No Path" );
}
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
let x = 5;
printPath(root, x);
</script>
|
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:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
Node( int value){
data = value;
left = right = NULL;
}
};
void printPath(Node* root, int target) {
vector< int > path;
stack<Node*> nodeStack;
Node* curr = root;
Node* prev = NULL;
while (curr || !nodeStack.empty()){
while (curr){
nodeStack.push(curr);
path.push_back(curr->data);
curr = curr->left;
}
curr = nodeStack.top();
if (curr->right && curr->right != prev){
curr = curr->right;
} else {
if (curr->data == target){
for ( int i = 0; i<path.size()-1; i++)
cout<<path[i]<< "->" ;
cout<<path[path.size()-1]<<endl;
return ;
}
nodeStack.pop();
path.pop_back();
prev = curr;
curr = NULL;
}
}
cout<< "No Path" <<endl;
}
int main() {
Node *root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
int target = 5;
printPath(root, target);
return 0;
}
|
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.
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.