原题链接:https://leetcode.cn/problems/create-binary-tree-from-descriptions/
class Solution {
public:
TreeNode* createBinaryTree(vector<vector<int>>& descriptions) {
unordered_map<int, TreeNode*> mp;
unordered_map<int, bool> isRoot;
for (auto desc : descriptions) {
int p = desc[0], c = desc[1];
if (!mp.count(p)) {
mp[p] = new TreeNode(p);
}
if (!mp.count(c)) {
mp[c] = new TreeNode(c);
}
if (!isRoot.count(p)) {
isRoot[p] = true;
}
isRoot[c] = false;
TreeNode* node = mp[p];
TreeNode* child = mp[c];
if (desc[2]) {
node->left = child;
} else {
node->right = child;
}
}
for (auto [k, v] : isRoot) {
if (v) return mp[k];
}
return NULL;
}
};
|