# trie树-leetcode-421. Maximum XOR of Two Numbers in an Array

C++代码：

``````class Solution {
public:
struct TrieNode {
TrieNode *child[2];
TrieNode() {
child[0] = NULL;
child[1] = NULL;
}
};
TrieNode *buildTree(vector<int> &nums) {
TrieNode *root = new TrieNode();
TrieNode *cur = NULL;
int n = nums.size();
for (int i=0; i<n; i++) {
cur = root;
for (int j = 31; j>=0; j--) {
int index = ((nums[i]>>j)&1);
if (cur->child[index] == NULL)
cur->child[index] = new TrieNode();
cur = cur->child[index];
}
}
return root;
}
int help(TrieNode * node, int num) {
int ret = 0;
for (int i=31; i>=0; i--) {
int index = ((num>>i)&1) ? 0 : 1;
if (node->child[index]) {
ret <<= 1;
ret |= 1;
node = node->child[index];
} else {
ret <<= 1;
node = node->child[index ? 0 : 1];
}

}
return ret;
}
int findMaximumXOR(vector<int>& nums) {
int ret = 0;
TrieNode *root = buildTree(nums);
for (int i=0; i<nums.size(); i++) {
ret = max(ret, help(root, nums[i]));
}
return ret;
}
};``````
原文作者：Trie树
原文地址: https://blog.csdn.net/u014257954/article/details/72513827
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。