Check if two nodes are in same subtree of the root node

Given a Binary Tree with distinct nodes. Given two nodes node1 and node2, check if the two nodes lies in the same subtree of the root node. That is, either of the left and right subtrees of the root node.
For Example: In the above binary tree, node 3 and 8 are in the same subtree but 4 and 5 are in different subtree.
Prerequisite: Check if a node exist in Binary Tree.
The idea is similar of searching a node in Binary Tree. There are four different cases:Â
- If both node1 and node2 are in left subtree of root node.
- If both node1 and node2 are in right subtree of the root node.
- If node1 is in the left subtree of the root node and node2 is in the right subtree of root node.
- If node1 is in the right subtree of the root node and node2 is in the left subtree of root node.
Use the approach of searching a node in Binary Tree and check if any of the first two cases listed above is True. If any of the first two cases listed above is found True then print YES otherwise print NO.
Below is the implementation of the above approach:Â
C++
// C++ program to check if two nodes// are in same subtrees of the root nodeÂ
#include <iostream>using namespace std;Â
// Binary tree nodestruct Node {Â Â Â Â int data;Â Â Â Â struct Node *left, *right;Â Â Â Â Node(int data)Â Â Â Â {Â Â Â Â Â Â Â Â this->data = data;Â Â Â Â Â Â Â Â left = right = NULL;Â Â Â Â }};Â
// Function to traverse the tree in preorder// and check if the given node exists in// a binary treebool ifNodeExists(struct Node* node, int key){Â Â Â Â if (node == NULL)Â Â Â Â Â Â Â Â return false;Â
    if (node->data == key)        return true;Â
    /* then recur on left subtree */    bool res1 = ifNodeExists(node->left, key);Â
    /* now recur on right subtree */    bool res2 = ifNodeExists(node->right, key);Â
    return res1 || res2;}Â
// Function to check if the two given nodes// are in same subtrees of the root nodebool ifSameSubTree(Node* root, int node1, int node2){Â Â Â Â if (root == NULL)Â Â Â Â Â Â Â return false;Â
    // CASE 1: If both nodes are in left subtree    if (ifNodeExists(root->left, node1)        && ifNodeExists(root->left, node2)) {        return true;    }Â
    // CASE 2: If both nodes are in right subtree    else if (ifNodeExists(root->right, node1)             && ifNodeExists(root->right, node2)) {        return true;    }Â
    // CASE 3 and 4: Nodes are in different subtrees    else        return false;}Â
// Driver Codeint main(){Â Â Â Â struct Node* root = new Node(0);Â Â Â Â root->left = new Node(1);Â Â Â Â root->left->left = new Node(3);Â Â Â Â root->left->left->left = new Node(7);Â Â Â Â root->left->right = new Node(4);Â Â Â Â root->left->right->left = new Node(8);Â Â Â Â root->left->right->right = new Node(9);Â Â Â Â root->right = new Node(2);Â Â Â Â root->right->left = new Node(5);Â Â Â Â root->right->right = new Node(6);Â
    int node1 = 3, node2 = 8;Â
    if (ifSameSubTree(root, node1, node2))        cout << "YES";    else        cout << "NO";Â
    return 0;} |
Java
// Java program to check if two nodes // are in same subtrees of the root node import java.util.*;class solution{Â
// Binary tree node  static class Node {     int data;      Node left, right;     Node(int data)     {         this.data = data;         left = right = null;     } } Â
// Function to traverse the tree in preorder // and check if the given node exists in // a binary tree static boolean ifNodeExists( Node node, int key) { Â Â Â Â if (node == null) Â Â Â Â Â Â Â Â return false; Â
    if (node.data == key)         return true; Â
    /* then recur on left subtree */    boolean res1 = ifNodeExists(node.left, key); Â
    /* now recur on right subtree */    boolean res2 = ifNodeExists(node.right, key); Â
    return res1 || res2; } Â
// Function to check if the two given nodes // are in same subtrees of the root node static boolean ifSameSubTree(Node root, int node1, int node2) { Â Â Â Â if (root == null) Â Â Â Â return false; Â
    // CASE 1: If both nodes are in left subtree     if (ifNodeExists(root.left, node1)         && ifNodeExists(root.left, node2)) {         return true;     } Â
    // CASE 2: If both nodes are in right subtree     else if (ifNodeExists(root.right, node1)             && ifNodeExists(root.right, node2)) {         return true;     } Â
    // CASE 3 and 4: Nodes are in different subtrees     else        return false; } Â
// Driver Code public static void main(String args[]){ Â Â Â Â Â Node root = new Node(0); Â Â Â Â root.left = new Node(1); Â Â Â Â root.left.left = new Node(3); Â Â Â Â root.left.left.left = new Node(7); Â Â Â Â root.left.right = new Node(4); Â Â Â Â root.left.right.left = new Node(8); Â Â Â Â root.left.right.right = new Node(9); Â Â Â Â root.right = new Node(2); Â Â Â Â root.right.left = new Node(5); Â Â Â Â root.right.right = new Node(6); Â
    int node1 = 3, node2 = 8; Â
    if (ifSameSubTree(root, node1, node2))         System.out.println("YES");     else        System.out.println( "NO"); Â
} }//contributed by Arnab Kundu |
Python3
"""Python3 program to check if two nodes are in same subtrees of the root node """Â
# A Binary Tree Node # Utility function to create a # new tree node class newNode: Â
    # Constructor to create a newNode     def __init__(self, data):         self.data= data         self.left = None        self.right = None        self.visited = FalseÂ
# Function to traverse the tree in # preorder and check if the given # node exists in a binary tree def ifNodeExists(node, key) :Â Â Â Â if (node == None):Â Â Â Â Â Â Â Â return FalseÂ
    if (node.data == key):        return TrueÂ
    """ then recur on left subtree """    res1 = ifNodeExists(node.left, key) Â
    """ now recur on right subtree """    res2 = ifNodeExists(node.right, key) Â
    return res1 or res2 Â
# Function to check if the two given nodes # are in same subtrees of the root node def ifSameSubTree(root, node1, node2):Â
    if (root == None) :        return FalseÂ
    # CASE 1: If both nodes are in    # left subtree     if (ifNodeExists(root.left, node1)         and ifNodeExists(root.left, node2)):        return TrueÂ
    # CASE 2: If both nodes are in     # right subtree     elif (ifNodeExists(root.right, node1)             and ifNodeExists(root.right, node2)):        return True         # CASE 3 and 4: Nodes are in     # different subtrees     else:        return False                         # Driver Codeif __name__ == '__main__':    root = newNode(0)     root.left = newNode(1)     root.left.left = newNode(3)     root.left.left.left = newNode(7)     root.left.right = newNode(4)     root.left.right.left = newNode(8)     root.left.right.right = newNode(9)     root.right = newNode(2)     root.right.left = newNode(5)     root.right.right = newNode(6) Â
    node1 = 3    node2 = 8Â
    if (ifSameSubTree(root, node1, node2)):        print("YES")     else:        print("NO")Â
# This code is contributed by # SHUBHAMSINGH10 |
C#
// C# program to check if two nodes // are in same subtrees of the root node using System;Â
class GFG{ Â
// Binary tree node class Node{ Â Â Â Â public int data; Â Â Â Â public Node left, right; Â Â Â Â public Node(int data) Â Â Â Â { Â Â Â Â Â Â Â Â this.data = data; Â Â Â Â Â Â Â Â left = right = null; Â Â Â Â } } Â
// Function to traverse the tree in preorder // and check if the given node exists in // a binary tree static bool ifNodeExists( Node node, int key) { Â Â Â Â if (node == null) Â Â Â Â Â Â Â Â return false; Â
    if (node.data == key)         return true; Â
    /* then recur on left subtree */    bool res1 = ifNodeExists(node.left, key); Â
    /* now recur on right subtree */    bool res2 = ifNodeExists(node.right, key); Â
    return res1 || res2; } Â
// Function to check if the two given nodes // are in same subtrees of the root node static bool ifSameSubTree(Node root,                int node1, int node2) {     if (root == null)     return false; Â
    // CASE 1: If both nodes are in left subtree     if (ifNodeExists(root.left, node1)         && ifNodeExists(root.left, node2))     {         return true;     } Â
    // CASE 2: If both nodes are in right subtree     else if (ifNodeExists(root.right, node1)             && ifNodeExists(root.right, node2))     {         return true;     } Â
    // CASE 3 and 4: Nodes are in different subtrees     else        return false; } Â
// Driver Code public static void Main() { Â Â Â Â Node root = new Node(0); Â Â Â Â root.left = new Node(1); Â Â Â Â root.left.left = new Node(3); Â Â Â Â root.left.left.left = new Node(7); Â Â Â Â root.left.right = new Node(4); Â Â Â Â root.left.right.left = new Node(8); Â Â Â Â root.left.right.right = new Node(9); Â Â Â Â root.right = new Node(2); Â Â Â Â root.right.left = new Node(5); Â Â Â Â root.right.right = new Node(6); Â
    int node1 = 3, node2 = 8; Â
    if (ifSameSubTree(root, node1, node2))         Console.WriteLine("YES");     else        Console.WriteLine( "NO"); Â
} } Â
/* This code is contributed by Rajput-Ji*/ |
Javascript
<script>Â
// JavaScript program to check if two nodes // are in same subtrees of the root node Â
    // Binary tree nodeclass Node {    constructor(val) {        this.data = val;        this.left = null;        this.right = null;    }}Â
    // Function to traverse the tree in preorder    // and check if the given node exists in    // a binary tree    function ifNodeExists(node , key) {        if (node == null)            return false;Â
        if (node.data == key)            return true;Â
        /* then recur on left subtree */        var res1 = ifNodeExists(node.left, key);Â
        /* now recur on right subtree */        var res2 = ifNodeExists(node.right, key);Â
        return res1 || res2;    }Â
    // Function to check if the two given nodes    // are in same subtrees of the root node    function ifSameSubTree(root , node1 , node2) {        if (root == null)            return false;Â
        // CASE 1: If both nodes are in left subtree        if (ifNodeExists(root.left, node1) &&         ifNodeExists(root.left, node2)) {            return true;        }Â
        // CASE 2: If both nodes are in right subtree        else if (ifNodeExists(root.right, node1) &&         ifNodeExists(root.right, node2)) {            return true;        }Â
        // CASE 3 and 4: Nodes are in different subtrees        else            return false;    }Â
    // Driver Code             var root = new Node(0);        root.left = new Node(1);        root.left.left = new Node(3);        root.left.left.left = new Node(7);        root.left.right = new Node(4);        root.left.right.left = new Node(8);        root.left.right.right = new Node(9);        root.right = new Node(2);        root.right.left = new Node(5);        root.right.right = new Node(6);Â
        var node1 = 3, node2 = 8;Â
        if (ifSameSubTree(root, node1, node2))            document.write("YES");        else            document.write("NO");Â
// This code is contributed by todaysgauravÂ
</script> |
YES
Complexity Analysis:
- Time Complexity: O(N), as we are using recursion to traverse N nodes of the tree for checking if the nodes exists. Where N is the number of nodes in the tree.
- Auxiliary Space: O(N), as though we are not using any explicit extra space but as we are using recursion a recursive call stack will be used which will cost O (N) space.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!




