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.
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:
Time Complexity: O(N)
Auxiliary Space: O(N), where N is the number of nodes.
- Print path between any two nodes in a Binary Tree
- Print path from root to all nodes in a Complete Binary Tree
- Shortest path between two nodes in array like representation of binary tree
- Minimum and maximum node that lies in the path connecting two nodes in a Binary Tree
- Maximum Path Sum in a Binary Tree
- Minimum sum path between two leaves of a binary tree
- Longest Path with Same Values in a Binary Tree
- Find the maximum path sum between two leaves of a binary tree
- Print path from root to a given node in a binary tree
- Sort the path from root to a given node in a Binary Tree
- Maximum Consecutive Increasing Path Length in Binary Tree
- Find the maximum sum leaf to root path in a Binary Tree
- Print the first shortest root to leaf path in a Binary Tree
- Sum of all nodes in a binary tree
- Product of all nodes in a Binary Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.