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:
- 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++
// C++ implementation to print the path from root
// to a given node in a binary tree
#include <bits/stdc++.h>
using namespace std;
// structure of a node of binary tree
struct Node
{
int data;
Node *left, *right;
};
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct Node* getNode(int data)
{
struct Node *newNode = new Node;
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// Returns true if there is a path from root
// to the given node. It also populates
// 'arr' with the given path
bool hasPath(Node *root, vector<int>& arr, int x)
{
// if root is NULL
// there is no path
if (!root)
return false;
// push the node's value in 'arr'
arr.push_back(root->data);
// if it is the required node
// return true
if (root->data == x)
return true;
// else check whether the required node lies
// in the left subtree or right subtree of
// the current node
if (hasPath(root->left, arr, x) ||
hasPath(root->right, arr, x))
return true;
// required node does not lie either in the
// left or right subtree of the current node
// Thus, remove current node's value from
// 'arr'and then return false
arr.pop_back();
return false;
}
// function to print the path from root to the
// given node if the node lies in the binary tree
void printPath(Node *root, int x)
{
// vector to store the path
vector<int> arr;
// if required node 'x' is present
// then print the path
if (hasPath(root, arr, x))
{
for (int i=0; i<arr.size()-1; i++)
cout << arr[i] << "->";
cout << arr[arr.size() - 1];
}
// 'x' is not present in the binary tree
else
cout << "No Path";
}
// Driver program to test above
int main()
{
// binary tree formation
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
// Java implementation to print the path from root
// to a given node in a binary tree
import java.util.ArrayList;
public class PrintPath {
// Returns true if there is a path from root
// to the given node. It also populates
// 'arr' with the given path
public static boolean hasPath(Node root, ArrayList<Integer> arr, int x)
{
// if root is NULL
// there is no path
if (root==null)
return false;
// push the node's value in 'arr'
arr.add(root.data);
// if it is the required node
// return true
if (root.data == x)
return true;
// else check whether the required node lies
// in the left subtree or right subtree of
// the current node
if (hasPath(root.left, arr, x) ||
hasPath(root.right, arr, x))
return true;
// required node does not lie either in the
// left or right subtree of the current node
// Thus, remove current node's value from
// 'arr'and then return false
arr.remove(arr.size()-1);
return false;
}
// function to print the path from root to the
// given node if the node lies in the binary tree
public static void printPath(Node root, int x)
{
// ArrayList to store the path
ArrayList<Integer> arr=new ArrayList<>();
// if required node 'x' is present
// then print the path
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));
}
// 'x' is not present in the binary tree
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);
}
}
// A node of binary tree
class Node
{
int data;
Node left, right;
Node(int data)
{
this.data=data;
left=right=null;
}
};
//This code is contributed by Gaurav Tiwari
Python3
# Python3 implementation to print the path from
# root to a given node in a binary tree
# Helper Class that allocates a new node
# with the given data and None left and
# right pointers.
class getNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
# Returns true if there is a path from
# root to the given node. It also
# populates 'arr' with the given path
def hasPath(root, arr, x):
# if root is None there is no path
if (not root):
return False
# push the node's value in 'arr'
arr.append(root.data)
# if it is the required node
# return true
if (root.data == x):
return True
# else check whether the required node
# lies in the left subtree or right
# subtree of the current node
if (hasPath(root.left, arr, x) or
hasPath(root.right, arr, x)):
return True
# required node does not lie either in
# the left or right subtree of the current
# node. Thus, remove current node's value
# from 'arr'and then return false
arr.pop(-1)
return False
# function to print the path from root to
# the given node if the node lies in
# the binary tree
def printPath(root, x):
# vector to store the path
arr = []
# if required node 'x' is present
# then print the path
if (hasPath(root, arr, x)):
for i in range(len(arr) - 1):
print(arr[i], end = "->")
print(arr[len(arr) - 1])
# 'x' is not present in the
# binary tree
else:
print("No Path")
# Driver Code
if __name__ == '__main__':
# binary tree formation
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)
# This code is contributed by PranchalK
C#
// C# implementation to print the path from root
// to a given node in a binary tree
using System;
using System.Collections;
using System.Collections.Generic;
class PrintPath
{
// A node of binary tree
public class Node
{
public int data;
public Node left, right;
public Node(int data)
{
this.data = data;
left = right = null;
}
}
// Returns true if there is a path from root
// to the given node. It also populates
// 'arr' with the given path
public static Boolean hasPath(Node root,
List<int> arr, int x)
{
// if root is NULL
// there is no path
if (root == null)
return false;
// push the node's value in 'arr'
arr.Add(root.data);
// if it is the required node
// return true
if (root.data == x)
return true;
// else check whether the required node lies
// in the left subtree or right subtree of
// the current node
if (hasPath(root.left, arr, x) ||
hasPath(root.right, arr, x))
return true;
// required node does not lie either in the
// left or right subtree of the current node
// Thus, remove current node's value from
// 'arr'and then return false
arr.RemoveAt(arr.Count - 1);
return false;
}
// function to print the path from root to the
// given node if the node lies in the binary tree
public static void printPath(Node root, int x)
{
// List to store the path
List<int> arr = new List<int>();
// if required node 'x' is present
// then print the path
if (hasPath(root, arr, x))
{
for (int i = 0; i < arr.Count - 1; i++)
Console.Write(arr[i]+"->");
Console.Write(arr[arr.Count - 1]);
}
// 'x' is not present in the binary tree
else
Console.Write("No Path");
}
// Driver code
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);
}
}
// This code is contributed by Arnab Kundu
JavaScript
<script>
// Javascript implementation to print
// the path from root to a given node
// in a binary tree
class Node
{
constructor(data)
{
this.left = null;
this.right = null;
this.data = data;
}
}
// Returns true if there is a path from root
// to the given node. It also populates
// 'arr' with the given path
function hasPath(root, arr, x)
{
// If root is NULL
// there is no path
if (root == null)
return false;
// Push the node's value in 'arr'
arr.push(root.data);
// If it is the required node
// return true
if (root.data == x)
return true;
// Else check whether the required node lies
// in the left subtree or right subtree of
// the current node
if (hasPath(root.left, arr, x) ||
hasPath(root.right, arr, x))
return true;
// Required node does not lie either in the
// left or right subtree of the current node
// Thus, remove current node's value from
// 'arr'and then return false
arr.pop();
return false;
}
// Function to print the path from root to the
// given node if the node lies in the binary tree
function printPath(root, x)
{
// ArrayList to store the path
let arr = [];
// If required node 'x' is present
// then print the path
if (hasPath(root, arr, x))
{
for(let i = 0; i < arr.length - 1; i++)
document.write(arr[i] + "->");
document.write(arr[arr.length - 1]);
}
// 'x' is not present in the binary tree
else
document.write("No Path");
}
// Driver code
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);
// This code is contributed by divyeshrabadiya07
</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++
// C++ Program to print the path from root
// to a given node in binary tree
#include <bits/stdc++.h>
using namespace std;
// Structure of binary tree node
struct Node {
int data;
Node* left;
Node* right;
Node(int value){
data = value;
left = right = NULL;
}
};
// function which will print the path
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;
}
// Driver program to test above functions
int main() {
// Create a binary tree
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;
}
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)
Java
import java.util.Stack;
import java.util.Vector;
// Structure of binary tree node
class Node {
int data;
Node left, right;
public Node(int value) {
data = value;
left = right = null;
}
}
public class BinaryTreePath {
// function which will print the path
static void printPath(Node root, int target) {
Vector<Integer> path = new Vector<>();
Stack<Node> nodeStack = new Stack<>();
Node curr = root;
Node prev = null;
while (curr != null || !nodeStack.isEmpty()) {
while (curr != null) {
nodeStack.push(curr);
path.add(curr.data);
curr = curr.left;
}
curr = nodeStack.pop();
if (curr.right != null && curr.right != prev) {
curr = curr.right;
} else {
if (curr.data == target) {
for (int i = 0; i < path.size() - 1; i++)
System.out.print(path.get(i) + "->");
System.out.println(path.get(path.size() - 1));
return;
}
path.remove(path.size() - 1);
prev = curr;
curr = null;
}
}
System.out.println("No Path");
}
// Driver program to test above functions
public static void main(String[] args) {
// Create a binary tree
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);
}
}
Python3
class TreeNode:
def __init__(self, value):
self.data = value
self.left = None
self.right = None
def print_path(root, target):
path = []
node_stack = []
curr = root
prev = None
while curr or node_stack:
while curr:
node_stack.append(curr)
path.append(curr.data)
curr = curr.left
curr = node_stack[-1]
if curr.right and curr.right != prev:
curr = curr.right
else:
if curr.data == target:
print( "->".join(map(str, path)))
return
node_stack.pop()
path.pop()
prev = curr
curr = None
print("No Path")
# Driver program to test the function
if __name__ == "__main__":
# Create a binary tree
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)
target = 5
print_path(root, target)
C#
using System;
using System.Collections.Generic;
// Structure of binary tree node
public class Node {
public int data;
public Node left;
public Node right;
public Node(int value)
{
data = value;
left = right = null;
}
}
class Program {
// Function which will print the path
static void PrintPath(Node root, int target)
{
List<int> path = new List<int>();
Stack<Node> nodeStack = new Stack<Node>();
Node curr = root;
Node prev = null;
while (curr != null || nodeStack.Count > 0) {
while (curr != null) {
nodeStack.Push(curr);
path.Add(curr.data);
curr = curr.left;
}
curr = nodeStack.Peek();
if (curr.right != null && curr.right != prev) {
curr = curr.right;
}
else {
if (curr.data == target) {
for (int i = 0; i < path.Count - 1; i++)
Console.Write(path[i] + "->");
Console.WriteLine(path[path.Count - 1]);
return;
}
nodeStack.Pop();
path.RemoveAt(path.Count - 1);
prev = curr;
curr = null;
}
}
Console.WriteLine("No Path");
}
// Driver program to test above functions
static void Main()
{
// Create a binary tree
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);
}
}
JavaScript
// Structure of binary tree node
class Node {
constructor(value) {
this.data = value;
this.left = null;
this.right = null;
}
}
// Function to print the path from root to a given node
function printPath(root, target) {
let path = [];
let nodeStack = [];
let curr = root;
let prev = null;
while (curr || nodeStack.length > 0) {
while (curr) {
nodeStack.push(curr);
path.push(curr.data);
curr = curr.left;
}
curr = nodeStack[nodeStack.length - 1];
if (curr.right && curr.right !== prev) {
curr = curr.right;
} else {
if (curr.data === target) {
for (let i = 0; i < path.length - 1; i++) {
process.stdout.write(path[i] + "->");
}
console.log(path[path.length - 1]);
return;
}
nodeStack.pop();
path.pop();
prev = curr;
curr = null;
}
}
console.log("No Path");
}
// Driver code to test the above functions
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 target = 5;
printPath(root, target);
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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem