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 optimised recursive approach will be discussed.
In this recursive approach, below are the steps:

  1. Find the first value recursively, once found add the value to the stack.
  2. Now every node that is visited whether in backtracking or forward tracking, add 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:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
        }
  
        // Ccopy 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);
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
        }
  
        // Ccopy 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

chevron_right


Output:

7 3 1 4



My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : andrew1234

Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.