Given a tree with N distinct nodes from the range [1, n] and two integers x and val. The task is to find the maximum value of any node when XORed with x on the path from the root to val.
Input: val = 6, x = 4 1 / \ 2 3 / \ 4 5 / 6 Output: 7 the path is 1 -> 3 -> 5 -> 6 1 ^ 4 = 5 3 ^ 4 = 7 5 ^ 4 = 1 6 ^ 4 = 2 Maximum is 7 Input: val = 4, x = 1 1 / \ 2 3 / 4 Output: 5
- An optimized solution to the problem is to create a parent array to store the parent of each of the node.
- Start from the given node and keep on going up in the tree using the parent array (this will be helpful when answering a number of queries as only the nodes on the path will be traversed). Take the xor with x of all the nodes in the path till root.
- The maximum xor calculated for the path is the answer.
Below is the implementation of the above approach:
Time Complexity: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Count the number of paths from root to leaf of a Binary tree with given XOR value
- 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
- Sum of nodes in the path from root to N-th node in given Tree
- Count nodes having smallest value in the path from root to itself in a Binary Tree
- Count nodes having highest value in the path from root to itself in a Binary Tree
- Count nodes having Bitwise XOR of all edges in their path from the root equal to K
- Find the maximum sum leaf to root path in a Binary Tree
- Find the root of the sub-tree whose weighted sum XOR with X is maximum
- Maximum XOR path of a Binary Tree
- Find the path from root to the given nodes of a tree for multiple queries
- Maximum XOR value of maximum and second maximum element among all possible subarrays
- Find node U containing all nodes from a set V at atmost distance 1 from the path from root to U
- Sum of nodes on the longest path from root to leaf node
- Find maximum GCD value from root to leaf in a Binary tree
- Maximum value of Bitwise AND from root to leaf in a Binary tree
- Print path from root to all nodes in a Complete Binary Tree
- GCD from root to leaf path in an N-ary tree
- Boundary Root to Leaf Path traversal of 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 firstname.lastname@example.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.