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)
- 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
- Find the maximum sum leaf to root path in a Binary Tree
- Minimum and maximum node that lies in the path connecting two nodes in a Binary Tree
- Sum of nodes on the longest path from root to leaf node
- GCD from root to leaf path in an N-ary tree
- Root to leaf path with maximum distinct nodes
- Print the first shortest root to leaf path in a Binary Tree
- Find the path from root to the given nodes of a tree for multiple queries
- Print path from root to all nodes in a Complete Binary Tree
- Find root of the tree where children id sum for every node is given
- Find distance from root to given node in a binary tree
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Find the root of the sub-tree whose weighted sum XOR with X is maximum
- Maximum Path Sum 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.