![]() |
VOOZH | about |
Given a binary tree, where each node has a binary value, design an efficient algorithm to find the maximum XOR of any two node values in the tree.
Examples:
Input:
1
/ \
2 3
/ \ /
4 5 6
Output: 7
Explanation: 6 XOR 1 = 7Input:
1
/ \
5 2
/ \
9 3Output: 12
Explanation: 9 XOR 5 = 12
Naive Approach: A simple solution is to generate all pairs, find their XOR values, and finally return the maximum XOR value. But its time and space complexity will be very high.
Time Complexity: O(N2) where N is the number of nodes in the given tree.
Auxiliary Space: O(1)
Efficient Approach: We can use a trie-based solution for this problem and utilize bit manipulation to efficiently store and retrieve values from the trie.
(root)
/ \
0 1
/ \ / \
0 1 1 0
/ | \
0 1 0Here, each node of the Trie has two children, 0 and 1. Each level of the Trie corresponds to a bit in the binary representation of the numbers. The root node corresponds to the most significant bit, and the leaf nodes correspond to the least significant bit. The numbers in the above example have the following binary representation:
- 1 = 001
- 2 = 010
- 3 = 011
- 4 = 100
- 5 = 101
- 6 = 110
Thus, the Trie structure can be represented in the form of bits of nodes 0 and 1 as follows:
Bitwise representation of trie:
- Level 2: 0 1
- Level 1: 0 1 1 0
- Level 0: 0 1 0 1 1 0
Idea/Intuition:
- Construct a trie from the binary representation of the node values in the tree, where each node in the trie corresponds to a bit in the binary representation and the path from the root of the trie to a leaf node represents the binary value of a node in the tree.
- Starting from the most significant bit, traverse the trie to find a pair of node values that have different bits at the current position. If such a pair exists, it contributes to the maximum XOR.
- To find the pair, check if both 0 and 1 child nodes exist at the current position. If they do, continue the search in the corresponding child node with the opposite bit. If only one child node exists, continue the search in that node.
- Repeat the above step for all the bits, updating the XOR value with the corresponding bit value each time.
- Return the final XOR value as the result.
Note: The trie can be constructed efficiently using a recursive approach that traverses the tree in a post-order manner and inserts each node value into the trie as it is processed.
Steps to follow to implement the approach:
Below is the implementation of the above approach:
,
Maximum XOR: 7
Time Complexity: O(N), where N is the number of nodes in the tree since each node in the tree is processed only once during the construction of the trie and the search.
Auxiliary Space: O(N), since the size of the trie is proportional to the number of nodes in the tree.