Print path between any two nodes in a Binary Tree | Set 2
Last Updated :
12 Jul, 2025
Given a Binary Tree of distinct nodes and a pair of nodes. The task is to find and print the path between the two given nodes in the binary tree.
Examples:
Input: N1 = 7, N2 = 4
Output: 7 3 1 4
Approach: An approach to solve this problem has been discussed in this article. In this article, an even optimized recursive approach will be discussed.
In this recursive approach, below are the steps:
- Find the first value recursively, once found add the value to the stack.
- Now every node that is visited whether in backtracking or forward tracking, adds the values to the stack but if the node was added in the forward tracking then remove it in the backtracking and continue this until the second value is found or all nodes are visited.
For example: Consider the path between 7 and 9 is to be found in the above tree. We traverse the tree as DFS, once we find the value 7, we add it to the stack. Traversing path 0 -> 1 -> 3 -> 7.
Now while backtracking, add 3 and 1 to the stack. So as of now, the stack has [7, 3, 1], child 1 has a right child, so we first add it to the stack. Now, the stack contains [7, 3, 1, 4]. Visit the left child of 4, add it to the stack. The stack contains [7, 3, 1, 4, 8] now. Since there is no further node we would go back to the previous node and since 8 was already added to the stack so remove it. Now the node 4 has a right child, and we add it to the stack since this is the second value we were looking for there won't be any further recursive calls. Finally, the stack contains [7, 3, 1, 4, 9].
Below is the implementation of the above approach:
C++
// CPP implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// A binary tree node
class Node {
public:
int value;
Node *left, *right;
Node(int value) {
this->value = value;
left = NULL;
right = NULL;
}
};
bool firstValueFound = false;
bool secondValueFound = false;
stack<Node *> stk;
Node *root = NULL;
// Function to find the path between
// two nodes in binary tree
void pathBetweenNode(Node *root, int v1, int v2) {
// Base condition
if (root == NULL) return;
// If both the values are found then return
if (firstValueFound && secondValueFound) return;
// Starting the stack frame with
// isAddedToStack = false flag
bool isAddedToStack = false;
// If one of the value is found then add the
// value to the stack and make the isAddedToStack = true
if (firstValueFound ^ secondValueFound) {
stk.push(root);
isAddedToStack = true;
}
// If none of the two values is found
if (!(firstValueFound && secondValueFound)) {
pathBetweenNode(root->left, v1, v2);
}
// Copy of current state of firstValueFound
// and secondValueFound flag
bool localFirstValueFound = firstValueFound;
bool localSecondValueFound = secondValueFound;
// If the first value is found
if (root->value == v1) firstValueFound = true;
// If the second value is found
if (root->value == v2) secondValueFound = true;
bool localAdded = false;
// If one of the value is found and the value
// was not added to the stack yet or there was
// only one value found and now both the values
// are found and was not added to
// the stack then add it
if (((firstValueFound ^ secondValueFound) ||
((localFirstValueFound ^ localSecondValueFound) &&
(firstValueFound && secondValueFound))) &&
!isAddedToStack) {
localAdded = true;
stk.push(root);
}
// If none of the two values is found yet
if (!(firstValueFound && secondValueFound)) {
pathBetweenNode(root->right, v1, v2);
}
if ((firstValueFound ^ secondValueFound) && !isAddedToStack && !localAdded)
stk.push(root);
if ((firstValueFound ^ secondValueFound) && isAddedToStack) stk.pop();
}
// Function to find the path between
// two nodes in binary tree
stack<Node *> pathBetweenNode(int v1, int v2)
{
// Global root
pathBetweenNode(::root, v1, v2);
// If both the values are found
// then return the stack
if (firstValueFound && secondValueFound)
{
// Global Stack Object
return ::stk;
}
// If none of the two values is
// found then return empty stack
stack<Node *> stk;
return stk;
}
// Recursive function to print the
// contents of a stack in reverse
void print(stack<Node *> stk)
{
// If the stack is empty
if (stk.empty()) return;
// Get the top value
int value = stk.top()->value;
stk.pop();
// Recursive call
print(stk);
// Print the popped value
cout << value << " ";
}
// Driver code
int main(int argc, char const *argv[])
{
root = new Node(0);
root->left = new Node(1);
root->right = new Node(2);
root->left->left = new Node(3);
root->left->right = new Node(4);
root->right->left = new Node(5);
root->right->right = new Node(6);
root->left->left->left = new Node(7);
root->left->right->left = new Node(8);
root->left->right->right = new Node(9);
// Find and print the path
stack<Node *> stck = pathBetweenNode(7, 4);
print(stck);
}
// This code is contributed by sanjeev2552
Java
// Java implementation of the approach
import java.util.Stack;
public class GFG {
// A binary tree node
private static class Node {
public Node left;
public int value;
public Node right;
public Node(int value)
{
this.value = value;
left = null;
right = null;
}
}
private boolean firstValueFound = false;
private boolean secondValueFound = false;
private Stack<Node> stack = new Stack<Node>();
private Node root = null;
public GFG(Node root)
{
this.root = root;
}
// Function to find the path between
// two nodes in binary tree
public Stack<Node> pathBetweenNode(int v1, int v2)
{
pathBetweenNode(this.root, v1, v2);
// If both the values are found
// then return the stack
if (firstValueFound && secondValueFound) {
return stack;
}
// If none of the two values is
// found then return empty stack
return new Stack<Node>();
}
// Function to find the path between
// two nodes in binary tree
private void pathBetweenNode(Node root, int v1, int v2)
{
// Base condition
if (root == null)
return;
// If both the values are found then return
if (firstValueFound && secondValueFound)
return;
// Starting the stack frame with
// isAddedToStack = false flag
boolean isAddedToStack = false;
// If one of the value is found then add the
// value to the stack and make the isAddedToStack = true
if (firstValueFound ^ secondValueFound) {
stack.add(root);
isAddedToStack = true;
}
// If none of the two values is found
if (!(firstValueFound && secondValueFound)) {
pathBetweenNode(root.left, v1, v2);
}
// Copy of current state of firstValueFound
// and secondValueFound flag
boolean localFirstValueFound = firstValueFound;
boolean localSecondValueFound = secondValueFound;
// If the first value is found
if (root.value == v1)
firstValueFound = true;
// If the second value is found
if (root.value == v2)
secondValueFound = true;
boolean localAdded = false;
// If one of the value is found and the value
// was not added to the stack yet or there was
// only one value found and now both the values
// are found and was not added to
// the stack then add it
if (((firstValueFound ^ secondValueFound)
|| ((localFirstValueFound ^ localSecondValueFound)
&& (firstValueFound && secondValueFound)))
&& !isAddedToStack) {
localAdded = true;
stack.add(root);
}
// If none of the two values is found yet
if (!(firstValueFound && secondValueFound)) {
pathBetweenNode(root.right, v1, v2);
}
if ((firstValueFound ^ secondValueFound)
&& !isAddedToStack && !localAdded)
stack.add(root);
if ((firstValueFound ^ secondValueFound)
&& isAddedToStack)
stack.pop();
}
// Recursive function to print the
// contents of a stack in reverse
private static void print(Stack<Node> stack)
{
// If the stack is empty
if (stack.isEmpty())
return;
// Get the top value
int value = stack.pop().value;
// Recursive call
print(stack);
// Print the popped value
System.out.print(value + " ");
}
// Driver code
public static void main(String[] args)
{
Node root = new Node(0);
root.left = new Node(1);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(4);
root.right.left = new Node(5);
root.right.right = new Node(6);
root.left.left.left = new Node(7);
root.left.right.left = new Node(8);
root.left.right.right = new Node(9);
// Find and print the path
GFG pathBetweenNodes = new GFG(root);
Stack<Node> stack
= pathBetweenNodes.pathBetweenNode(7, 4);
print(stack);
}
}
Python3
# Python3 implementation of
# the above approach
# A binary tree node
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
firstValueFound = False
secondValueFound = False
stack = []
root = None
# Function to find the path
# between two nodes in binary
# tree
def pathBetweennode(v1, v2):
global firstValueFound, secondValueFound
pathBetweenNode(root, v1, v2)
# If both the values are found
# then return the stack
if (firstValueFound and
secondValueFound):
return stack
# If none of the two values is
# found then return empty stack
return []
# Function to find the path
# between two nodes in binary
# tree
def pathBetweenNode(root,
v1, v2):
global firstValueFound, secondValueFound
# Base condition
if (root == None):
return
# If both the values are found
# then return
if (firstValueFound and
secondValueFound):
return
# Starting the stack frame with
# isAddedToStack = false flag
isAddedToStack = False
# If one of the value is found
# then add the value to the
# stack and make the isAddedToStack = true
if (firstValueFound ^ secondValueFound):
stack.append(root)
isAddedToStack = True
# If none of the two values
# is found
if (not (firstValueFound and
secondValueFound)):
pathBetweenNode(root.left,
v1, v2)
# Copy of current state of
# firstValueFound and
# secondValueFound flag
localFirstValueFound = firstValueFound
localSecondValueFound = secondValueFound
# If the first value is found
if (root.value == v1):
firstValueFound = True
# If the second value is found
if (root.value == v2):
secondValueFound = True
localAdded = False
# If one of the value is found
# and the value was not added
# to the stack yet or there was
# only one value found and now
# both the values are found and
# was not added to the stack
# then add it
if (((firstValueFound ^
secondValueFound) or
((localFirstValueFound ^
localSecondValueFound) and
(firstValueFound and
secondValueFound))) and
not isAddedToStack):
localAdded = True
stack.append(root)
# If none of the two values
# is found yet
if (not (firstValueFound and
secondValueFound)):
pathBetweenNode(root.right,
v1, v2)
if ((firstValueFound ^
secondValueFound) and
not isAddedToStack and
not localAdded):
stack.append(root)
if ((firstValueFound ^
secondValueFound) and
isAddedToStack):
stack.pop()
# Recursive function to print
# the contents of a stack in
# reverse
def pri(stack):
# If the stack is empty
if (len(stack) == 0):
return
# Get the top value
value = stack.pop().value
# Recursive call
pri(stack)
# Print the popped value
print(value, end = " ")
# Driver code
if __name__ == "__main__":
root = Node(0)
root.left = Node(1)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(4)
root.right.left = Node(5)
root.right.right = Node(6)
root.left.left.left = Node(7)
root.left.right.left = Node(8)
root.left.right.right = Node(9)
# Find and print the path
stack = pathBetweennode(7, 4)
pri(stack)
# This code is contributed by Rutvik_56
C#
// C# implementation of the approach
using System;
using System.Collections;
using System.Collections.Generic;
class GFG
{
// A binary tree node
public class Node
{
public Node left;
public int value;
public Node right;
public Node(int value)
{
this.value = value;
left = null;
right = null;
}
}
private Boolean firstValueFound = false;
private Boolean secondValueFound = false;
private Stack<Node> stack = new Stack<Node>();
private Node root = null;
public GFG(Node root)
{
this.root = root;
}
// Function to find the path between
// two nodes in binary tree
public Stack<Node> pathBetweenNode(int v1, int v2)
{
pathBetweenNode(this.root, v1, v2);
// If both the values are found
// then return the stack
if (firstValueFound && secondValueFound)
{
return stack;
}
// If none of the two values is
// found then return empty stack
return new Stack<Node>();
}
// Function to find the path between
// two nodes in binary tree
private void pathBetweenNode(Node root, int v1, int v2)
{
// Base condition
if (root == null)
return;
// If both the values are found then return
if (firstValueFound && secondValueFound)
return;
// Starting the stack frame with
// isAddedToStack = false flag
Boolean isAddedToStack = false;
// If one of the value is found then add the
// value to the stack and make the isAddedToStack = true
if (firstValueFound ^ secondValueFound)
{
stack.Push(root);
isAddedToStack = true;
}
// If none of the two values is found
if (!(firstValueFound && secondValueFound))
{
pathBetweenNode(root.left, v1, v2);
}
// Copy of current state of firstValueFound
// and secondValueFound flag
Boolean localFirstValueFound = firstValueFound;
Boolean localSecondValueFound = secondValueFound;
// If the first value is found
if (root.value == v1)
firstValueFound = true;
// If the second value is found
if (root.value == v2)
secondValueFound = true;
Boolean localAdded = false;
// If one of the value is found and the value
// was not added to the stack yet or there was
// only one value found and now both the values
// are found and was not added to
// the stack then add it
if (((firstValueFound ^ secondValueFound)
|| ((localFirstValueFound ^ localSecondValueFound)
&& (firstValueFound && secondValueFound)))
&& !isAddedToStack)
{
localAdded = true;
stack.Push(root);
}
// If none of the two values is found yet
if (!(firstValueFound && secondValueFound))
{
pathBetweenNode(root.right, v1, v2);
}
if ((firstValueFound ^ secondValueFound)
&& !isAddedToStack && !localAdded)
stack.Push(root);
if ((firstValueFound ^ secondValueFound)
&& isAddedToStack)
stack.Pop();
}
// Recursive function to print the
// contents of a stack in reverse
private static void print(Stack<Node> stack)
{
// If the stack is empty
if (stack.Count==0)
return;
// Get the top value
int value = stack.Pop().value;
// Recursive call
print(stack);
// Print the Popped value
Console.Write(value + " ");
}
// Driver code
public static void Main(String []args)
{
Node root = new Node(0);
root.left = new Node(1);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(4);
root.right.left = new Node(5);
root.right.right = new Node(6);
root.left.left.left = new Node(7);
root.left.right.left = new Node(8);
root.left.right.right = new Node(9);
// Find and print the path
GFG pathBetweenNodes = new GFG(root);
Stack<Node> stack
= pathBetweenNodes.pathBetweenNode(7, 4);
print(stack);
}
}
// This code is contributed by Arnab Kundu
JavaScript
<script>
// JavaScript implementation of the approach
// A binary tree node
class Node {
constructor(value) {
this.left = null;
this.right = null;
this.value = value;
}
}
let firstValueFound = false;
let secondValueFound = false;
let stack = [];
let root = null;
// Function to find the path between
// two nodes in binary tree
function path_BetweenNode(root, v1, v2)
{
// Base condition
if (root == null)
return;
// If both the values are found then return
if (firstValueFound && secondValueFound)
return;
// Starting the stack frame with
// isAddedToStack = false flag
let isAddedToStack = false;
// If one of the value is found then add the
// value to the stack and make the isAddedToStack = true
if (firstValueFound ^ secondValueFound) {
stack.push(root);
isAddedToStack = true;
}
// If none of the two values is found
if (!(firstValueFound && secondValueFound)) {
path_BetweenNode(root.left, v1, v2);
}
// Copy of current state of firstValueFound
// and secondValueFound flag
let localFirstValueFound = firstValueFound;
let localSecondValueFound = secondValueFound;
// If the first value is found
if (root.value == v1)
firstValueFound = true;
// If the second value is found
if (root.value == v2)
secondValueFound = true;
let localAdded = false;
// If one of the value is found and the value
// was not added to the stack yet or there was
// only one value found and now both the values
// are found and was not added to
// the stack then add it
if (((firstValueFound ^ secondValueFound)
|| ((localFirstValueFound ^ localSecondValueFound)
&& (firstValueFound && secondValueFound)))
&& !isAddedToStack) {
localAdded = true;
stack.push(root);
}
// If none of the two values is found yet
if (!(firstValueFound && secondValueFound)) {
path_BetweenNode(root.right, v1, v2);
}
if ((firstValueFound ^ secondValueFound)
&& !isAddedToStack && !localAdded)
stack.push(root);
if ((firstValueFound ^ secondValueFound)
&& isAddedToStack)
stack.pop();
}
// Function to find the path between
// two nodes in binary tree
function pathBetweenNode(v1, v2)
{
path_BetweenNode(root, v1, v2);
// If both the values are found
// then return the stack
if (firstValueFound && secondValueFound) {
return stack;
}
// If none of the two values is
// found then return empty stack
return [];
}
// Recursive function to print the
// contents of a stack in reverse
function print(stack)
{
// If the stack is empty
if (stack.length == 0)
return;
// Get the top value
let value = stack[stack.length - 1].value;
stack.pop();
// Recursive call
print(stack);
// Print the popped value
document.write(value + " ");
}
root = new Node(0);
root.left = new Node(1);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(4);
root.right.left = new Node(5);
root.right.right = new Node(6);
root.left.left.left = new Node(7);
root.left.right.left = new Node(8);
root.left.right.right = new Node(9);
// Find and print the path
stack = pathBetweenNode(7, 4);
print(stack);
</script>
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