XOR of path between any two nodes in a Binary Tree

28 Jun, 2021
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 these two properties of XOR:  
XOR of same elements is zero.
XOR of an element with zero gives the element itself.
Now, for each node find and store the XOR along the path from root to that node. This can be done using simple DFS. Now the XOR along path between any two nodes will be:  
(XOR of path from root to first node) XOR (XOR of path from root to second node)
Explanation: There arises two different cases:  
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 the formulae written above will give the correct result as the path between the nodes goes through root with all distinct nodes.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 root. The XOR of this common path is calculated twice and cancels out, so it does not effect the result.
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 the formulae written above will give the correct result as the path between the nodes goes through root with all distinct nodes.
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 root. The XOR of this common path is calculated twice and cancels out, so it does not effect the result.
Note: For a single pair of nodes, it is not needed to store the path from roots to all nodes. This is efficient and written considering if there is a list of pair of nodes and for every pair we have to find XOR of path between the two nodes in a Binary Tree.Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ program to find XOR of path between// any two nodes in a Binary Tree#include <bits/stdc++.h>using namespace std; // structure of a node of binary treestruct Node {    int data;    Node *left, *right;}; /* Helper function that allocates a new node with thegiven 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 store XOR of path from// root to every node// mp[x] will store XOR of path from root to node xvoid storePath(Node* root, unordered_map<int, int>& mp, int XOR){    // if root is NULL    // there is no path    if (!root)        return;     mp.insert(make_pair(root->data, XOR ^ root->data));     XOR ^= root->data;     if (root->left)        storePath(root->left, mp, XOR);     if (root->right)        storePath(root->right, mp, XOR);} // Function to get XOR of nodes between any two nodesint findXORPath(unordered_map<int, int> mp, int node1, int node2){    return mp[node1] ^ mp[node2];} // Driver Codeint 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 XOR = 0;    unordered_map<int, int> mp;     int node1 = 3;    int node2 = 5;     // Store XOR path from root to every node    storePath(root, mp, XOR);     cout << findXORPath(mp, node1, node2);     return 0;}
// Java program to find XOR of path between// any two nodes in a Binary Treeimport java.util.*;class Solution{ // structure of a node of binary treestatic class Node {    int data;    Node left, right;} /* Helper function that allocates a new node with thegiven 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 store XOR of path from// root to every node// mp[x] will store XOR of path from root to node xstatic void storePath(Node root, Map<Integer, Integer> mp, int XOR){    // if root is null    // there is no path    if (root==null)        return;     mp.put(root.data, XOR ^ root.data);     XOR ^= root.data;     if (root.left!=null)        storePath(root.left, mp, XOR);     if (root.right!=null)        storePath(root.right, mp, XOR);} // Function to get XOR of nodes between any two nodesstatic int findXORPath(Map<Integer, Integer> mp, int node1, int node2){    return mp.get(node1) ^ mp.get(node2);} // Driver Codepublic 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 XOR = 0;    Map<Integer, Integer> mp= new HashMap<Integer, Integer>();     int node1 = 3;    int node2 = 5;     // Store XOR path from root to every node    storePath(root, mp, XOR);     System.out.println( findXORPath(mp, node1, node2)); }}//contributed by Arnab Kundu
# Python3 program to find XOR of path between# any two nodes in a Binary Tree # Tree nodeclass Node:    def __init__(self, data):        self.data = data        self.left = None        self.right = None # Helper function that allocates a node with the# given data and None left and right pointers.def getNode(data):     newNode = Node(0)    newNode.data = data    newNode.left = newNode.right = None    return newNode mp = dict() # Function to store XOR of path from# root to every node# mp[x] will store XOR of path from root to node xdef storePath( root, XOR) :    global mp         # if root is None    # there is no path    if (root == None) :        return     mp[root.data] = XOR ^ root.data;     XOR = XOR ^ root.data     if (root.left != None):        storePath(root.left, XOR)     if (root.right != None) :        storePath(root.right, XOR) # Function to get XOR of nodes between any two nodesdef findXORPath( node1, node2) :    global mp    return mp.get(node1,0) ^ mp.get(node2,0) # Driver Code # binary tree formationroot = 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) XOR = 0 node1 = 3node2 = 5 # Store XOR path from root to every nodestorePath(root, XOR) print( findXORPath( node1, node2)) # This code is contributed by Arnab Kundu
// C# program to find XOR of path between// any two nodes in a Binary Treeusing System;using System.Collections.Generic; class GFG{     // structure of a node of binary tree    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 store XOR of path from    // root to every node    // mp[x] will store XOR of path from root to node x    static void storePath(Node root,                Dictionary<int, int> mp, int XOR)    {        // if root is null        // there is no path        if (root == null)            return;         mp.Add(root.data, XOR ^ root.data);         XOR ^= root.data;         if (root.left != null)            storePath(root.left, mp, XOR);         if (root.right != null)            storePath(root.right, mp, XOR);    }     // Function to get XOR of nodes between any two nodes    static int findXORPath(Dictionary<int, int> mp,                            int node1, int node2)    {        return mp[node1] ^ mp[node2];    }     // Driver Code    public static void Main()    {        // 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 XOR = 0;        Dictionary<int, int> mp = new Dictionary<int, int>();         int node1 = 3;        int node2 = 5;         // Store XOR path from root to every node        storePath(root, mp, XOR);         Console.WriteLine( findXORPath(mp, node1, node2));    }} /* This code is contributed PrinciRaj1992 */
<script>     // JavaScript program to find XOR of path between    // any two nodes in a Binary Tree         // structure of a node of 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 store XOR of path from    // root to every node    // mp[x] will store XOR of path from root to node x    function storePath(root, mp, XOR)    {        // if root is null        // there is no path        if (root==null)            return;         mp.set(root.data, XOR ^ root.data);         XOR ^= root.data;         if (root.left!=null)            storePath(root.left, mp, XOR);         if (root.right!=null)            storePath(root.right, mp, XOR);    }     // Function to get XOR of nodes between any two nodes    function findXORPath(mp, node1, node2)    {        return mp.get(node1) ^ mp.get(node2);    }         // 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 XOR = 0;    let mp= new Map();       let node1 = 3;    let node2 = 5;       // Store XOR path from root to every node    storePath(root, mp, XOR);       document.write(findXORPath(mp, node1, node2)); </script>
5
 
Time Complexity: O(N) Auxiliary Space: O(N), where N is the number of nodes. 
andrew1234
princiraj1992
rameshtravel07
Binary Tree
Bitwise-XOR
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Introduction to Tree Data Structure
Inorder Tree Traversal without Recursion
What is Data Structure: Types, Classifications and Applications
Binary Tree | Set 3 (Types of Binary Tree)
Lowest Common Ancestor in a Binary Tree | Set 1
Binary Tree | Set 2 (Properties)
Diameter of a Binary Tree
Decision Tree
Construct Tree from given Inorder and Preorder traversals