Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
All nodes between two given levels in Binary Tree
Next article icon

Print path between any two nodes in a Binary Tree

Last Updated : 08 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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.
 

For Example, in the above binary tree the path between the nodes 7 and 4 is 7 -> 3 -> 1 -> 4. 

The idea is to find paths from root nodes to the two nodes and store them in two separate vectors or arrays say path1 and path2.

Now, there arises two different cases: 

  1. If the two nodes are in different subtrees of root nodes. That is one in the left subtree and the other in the right subtree. In this case it is clear that root node will lie in between the path from node1 to node2. So, print path1 in reverse order and then path 2.
  2. If the nodes are in the same subtree. That is either in the left subtree or in the right subtree. In this case you need to observe that path from root to the two nodes will have an intersection point before which the path is common for the two nodes from the root node. Find that intersection point and print nodes from that point in a similar fashion of the above case.

Below is the implementation of the above approach: 

C++




// C++ program to print path between any
// two nodes 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;
}
 
// Function to check if there is a path from root
// to the given node. It also populates
// 'arr' with the given path
bool getPath(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 (getPath(root->left, arr, x) || getPath(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 between
// any two nodes in a binary tree
void printPathBetweenNodes(Node* root, int n1, int n2)
{
    // vector to store the path of
    // first node n1 from root
    vector<int> path1;
 
    // vector to store the path of
    // second node n2 from root
    vector<int> path2;
 
    getPath(root, path1, n1);
    getPath(root, path2, n2);
 
    int intersection = -1;
 
    // Get intersection point
    int i = 0, j = 0;
    while (i != path1.size() || j != path2.size()) {
 
        // Keep moving forward until no intersection
        // is found
        if (i == j && path1[i] == path2[j]) {
            i++;
            j++;
        }
        else {
            intersection = j - 1;
            break;
        }
    }
 
    // Print the required path
    for (int i = path1.size() - 1; i > intersection; i--)
        cout << path1[i] << " ";
 
    for (int i = intersection; i < path2.size(); i++)
        cout << path2[i] << " ";
}
 
// Driver program
int main()
{
    // binary tree formation
    struct Node* root = getNode(0);
    root->left = getNode(1);
    root->left->left = getNode(3);
    root->left->left->left = getNode(7);
    root->left->right = getNode(4);
    root->left->right->left = getNode(8);
    root->left->right->right = getNode(9);
    root->right = getNode(2);
    root->right->left = getNode(5);
    root->right->right = getNode(6);
 
    int node1 = 7;
    int node2 = 4;
    printPathBetweenNodes(root, node1, node2);
 
    return 0;
}
 
 

Java




// Java program to print path between any
// two nodes in a Binary Tree
import java.util.*;
class Solution
{
 
// structure of a node of binary tree
static class Node {
    int data;
    Node left, right;
}
 
/* Helper function that allocates a new node with the
given data and null left and right pointers. */
 static Node getNode(int data)
{
     Node newNode = new Node();
    newNode.data = data;
    newNode.left = newNode.right = null;
    return newNode;
}
 
// Function to check if there is a path from root
// to the given node. It also populates
// 'arr' with the given path
static boolean getPath(Node root, Vector<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 (getPath(root.left, arr, x) || getPath(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 between
// any two nodes in a binary tree
static void printPathBetweenNodes(Node root, int n1, int n2)
{
    // vector to store the path of
    // first node n1 from root
    Vector<Integer> path1= new Vector<Integer>();
 
    // vector to store the path of
    // second node n2 from root
    Vector<Integer> path2=new Vector<Integer>();
 
    getPath(root, path1, n1);
    getPath(root, path2, n2);
 
    int intersection = -1;
 
    // Get intersection point
    int i = 0, j = 0;
    while (i != path1.size() || j != path2.size()) {
 
        // Keep moving forward until no intersection
        // is found
        if (i == j && path1.get(i) == path2.get(i)) {
            i++;
            j++;
        }
        else {
            intersection = j - 1;
            break;
        }
    }
 
    // Print the required path
    for ( i = path1.size() - 1; i > intersection; i--)
        System.out.print( path1.get(i) + " ");
 
    for ( i = intersection; i < path2.size(); i++)
        System.out.print( path2.get(i) + " ");
}
 
// Driver program
public static void main(String[] args)
{
    // binary tree formation
     Node root = getNode(0);
    root.left = getNode(1);
    root.left.left = getNode(3);
    root.left.left.left = getNode(7);
    root.left.right = getNode(4);
    root.left.right.left = getNode(8);
    root.left.right.right = getNode(9);
    root.right = getNode(2);
    root.right.left = getNode(5);
    root.right.right = getNode(6);
 
    int node1 = 7;
    int node2 = 4;
    printPathBetweenNodes(root, node1, node2);
 
}
}
// This code is contributed by Arnab Kundu
 
 

Python




# Python3 program to print path between any
# two nodes in a Binary Tree
 
import sys
import math
 
# structure of a node of binary tree
class Node:
    def __init__(self,data):
        self.data = data
        self.left = None
        self.right = None
 
# Helper function that allocates a new node with the
#given data and NULL left and right pointers.
def getNode(data):
        return Node(data)
 
# Function to check if there is a path from root
# to the given node. It also populates
# 'arr' with the given path
def getPath(root, rarr, x):
 
    # if root is NULL
    # there is no path
    if not root:
        return False
     
    # push the node's value in 'arr'
    rarr.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 getPath(root.left, rarr, x) or getPath(root.right, rarr, 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
    rarr.pop()
    return False
 
# Function to print the path between
# any two nodes in a binary tree
def printPathBetweenNodes(root, n1, n2):
 
    # vector to store the path of
    # first node n1 from root
    path1 = []
 
    # vector to store the path of
    # second node n2 from root
    path2 = []
    getPath(root, path1, n1)
    getPath(root, path2, n2)
 
    # Get intersection point
    i, j = 0, 0
    intersection=-1
    while(i != len(path1) or j != len(path2)):
 
        # Keep moving forward until no intersection
        # is found
        if (i == j and path1[i] == path2[j]):
            i += 1
            j += 1
        else:
            intersection = j - 1
            break
 
    # Print the required path
    for i in range(len(path1) - 1, intersection - 1, -1):
        print("{} ".format(path1[i]), end = "")
    for j in range(intersection + 1, len(path2)):
        print("{} ".format(path2[j]), end = "")
     
# Driver program
if __name__=='__main__':
 
    # binary tree formation
    root = getNode(0)
    root.left = getNode(1)
    root.left.left = getNode(3)
    root.left.left.left = getNode(7)
    root.left.right = getNode(4)
    root.left.right.left = getNode(8)
    root.left.right.right = getNode(9)
    root.right = getNode(2)
    root.right.left = getNode(5)
    root.right.right = getNode(6)
    node1=7
    node2=4
    printPathBetweenNodes(root,node1,node2)
 
# This Code is Contributed By Vikash Kumar 37
 
 

C#




// C# program to print path between any
// two nodes in a Binary Tree
using System;
using System.Collections.Generic;
 
class Solution
{
 
// structure of a node of binary tree
public class Node
{
    public int data;
    public Node left, right;
}
 
/* Helper function that allocates a new node with the
given data and null left and right pointers. */
static Node getNode(int data)
{
    Node newNode = new Node();
    newNode.data = data;
    newNode.left = newNode.right = null;
    return newNode;
}
 
// Function to check if there is a path from root
// to the given node. It also populates
// 'arr' with the given path
static Boolean getPath(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 (getPath(root.left, arr, x) || getPath(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 between
// any two nodes in a binary tree
static void printPathBetweenNodes(Node root, int n1, int n2)
{
    // vector to store the path of
    // first node n1 from root
    List<int> path1 = new List<int>();
 
    // vector to store the path of
    // second node n2 from root
    List<int> path2 = new List<int>();
 
    getPath(root, path1, n1);
    getPath(root, path2, n2);
 
    int intersection = -1;
 
    // Get intersection point
    int i = 0, j = 0;
    while (i != path1.Count || j != path2.Count)
    {
 
        // Keep moving forward until no intersection
        // is found
        if (i == j && path1[i] == path2[i])
        {
            i++;
            j++;
        }
        else
        {
            intersection = j - 1;
            break;
        }
    }
 
    // Print the required path
    for ( i = path1.Count - 1; i > intersection; i--)
        Console.Write( path1[i] + " ");
 
    for ( i = intersection; i < path2.Count; i++)
        Console.Write( path2[i] + " ");
}
 
// Driver code
public static void Main(String[] args)
{
    // binary tree formation
    Node root = getNode(0);
    root.left = getNode(1);
    root.left.left = getNode(3);
    root.left.left.left = getNode(7);
    root.left.right = getNode(4);
    root.left.right.left = getNode(8);
    root.left.right.right = getNode(9);
    root.right = getNode(2);
    root.right.left = getNode(5);
    root.right.right = getNode(6);
 
    int node1 = 7;
    int node2 = 4;
    printPathBetweenNodes(root, node1, node2);
 
}
}
 
// This code is contributed by Princi Singh
 
 

Javascript




<script>
 
    // JavaScript program to print path between any
    // two nodes in a Binary Tree
     
    class Node
    {
        constructor(data) {
           this.left = null;
           this.right = null;
           this.data = data;
        }
    }
 
    /* Helper function that allocates a new node with the
    given data and null left and right pointers. */
    function getNode(data)
    {
        let newNode = new Node(data);
        return newNode;
    }
 
    // Function to check if there is a path from root
    // to the given node. It also populates
    // 'arr' with the given path
    function getPath(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 (getPath(root.left, arr, x) || getPath(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 between
    // any two nodes in a binary tree
    function printPathBetweenNodes(root, n1, n2)
    {
        // vector to store the path of
        // first node n1 from root
        let path1= [];
 
        // vector to store the path of
        // second node n2 from root
        let path2 = [];
 
        getPath(root, path1, n1);
        getPath(root, path2, n2);
 
        let intersection = -1;
 
        // Get intersection point
        let i = 0, j = 0;
        while (i != path1.length || j != path2.length) {
 
            // Keep moving forward until no intersection
            // is found
            if (i == j && path1[i] == path2[i]) {
                i++;
                j++;
            }
            else {
                intersection = j - 1;
                break;
            }
        }
 
        // Print the required path
        for ( i = path1.length - 1; i > intersection; i--)
            document.write( path1[i] + " ");
 
        for ( i = intersection; i < path2.length; i++)
            document.write( path2[i] + " ");
    }
     
    // binary tree formation
    let root = getNode(0);
    root.left = getNode(1);
    root.left.left = getNode(3);
    root.left.left.left = getNode(7);
    root.left.right = getNode(4);
    root.left.right.left = getNode(8);
    root.left.right.right = getNode(9);
    root.right = getNode(2);
    root.right.left = getNode(5);
    root.right.right = getNode(6);
   
    let node1 = 7;
    let node2 = 4;
    printPathBetweenNodes(root, node1, node2);
 
</script>
 
 
Output
7 3 1 4 

Complexity Analysis:

  • Time Complexity: O(N), as we are using recursion for traversing the tree. Where N is the number of nodes in the tree.
  • Auxiliary Space: O(N), as we are using extra space for storing the paths of the trees. Where N is the number of nodes in the tree.


Next Article
All nodes between two given levels in Binary Tree

S

Striver
Improve
Article Tags :
  • DSA
  • Tree
  • Binary Tree
  • Tree Traversals
Practice Tags :
  • Tree

Similar Reads

  • Print path between any two nodes in a Binary Tree | Set 2
    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 op
    15 min read
  • XOR of path between any two nodes in a Binary Tree
    Given a binary tree with distinct nodes and a pair of two nodes. The task is to find the XOR of all of the nodes which comes on the path between the given two nodes. For Example, in the above binary tree for nodes (3, 5) XOR of path will be (3 XOR 1 XOR 0 XOR 2 XOR 5) = 5. The idea is to make use of
    8 min read
  • Print all nodes between two given levels in Binary Tree
    Given a binary tree, the task is to print all nodes between two given levels in a binary tree. Print the nodes level-wise, i.e., the nodes for any level should be printed from left to right. Note: The levels are 1-indexed, i.e., root node is at level 1. Example: Input: Binary tree, l = 2, h = 3 Outp
    8 min read
  • Shortest path between two nodes in array like representation of binary tree
    Consider a binary tree in which each node has two children except the leaf nodes. If a node is labeled as 'v' then its right children will be labeled as 2v+1 and left children as 2v. Root is labelled asGiven two nodes labeled as i and j, the task is to find the shortest distance and the path from i
    12 min read
  • Print nodes between two given level numbers of a binary tree
    Given a binary tree and two level numbers 'low' and 'high', print nodes from level low to level high. For example consider the binary tree given in below diagram. Input: Root of below tree, low = 2, high = 4 Output: 8 22 4 12 10 14 A Simple Method is to first write a recursive function that prints n
    10 min read
  • Find distance between two nodes of a Binary Tree
    Given a Binary tree, the task is to find the distance between two keys in a binary tree, no parent pointers are given. The distance between two nodes is the minimum number of edges to be traversed to reach one node from another. The given two nodes are guaranteed to be in the binary tree and all nod
    15+ min read
  • Find path between lowest and highest value in a Binary tree
    Given a binary tree consisting of N nodes. Find the path between the node having the lowest value to the node having the highest value. There is no restriction on the traversal, i.e. the tree can be traversed upward, bottom, left and right. Examples: Input: N = 8 2 / \ 1 6 / \ \ 4 21 26 / \5 7 {(2),
    10 min read
  • Print all full nodes in a Binary Tree
    Given a binary tree, print all nodes will are full nodes. Full Nodes are nodes which has both left and right children as non-empty. Examples: Input : 10 / \ 8 2 / \ / 3 5 7 Output : 10 8 Input : 1 / \ 2 3 / \ 4 6 Output : 1 3 This is a simple problem. We do any of the tra­ver­sals (Inorder, Pre­orde
    4 min read
  • Shortest distance between two nodes in an infinite binary tree
    Consider you have an infinitely long binary tree having a pattern as below: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ / \ / \ / \ . . . . . . . . Given two nodes with values x and y. The task is to find the length of the shortest path between the two nodes. Examples: Input: x = 2, y = 3 Output: 2 Input: x = 4,
    15 min read
  • Print Ancestors of a given node in Binary Tree
    Given a Binary Tree and a key, write a function that prints all the ancestors of the key in the given binary tree. For example, if the given tree is following Binary Tree and the key is 7, then your function should print 4, 2, and 1. 1 / \ 2 3 / \ 4 5 / 7Recommended PracticeAncestors in Binary TreeT
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences