-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.cpp
32 lines (32 loc) · 986 Bytes
/
Solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* createBinaryTree(vector<vector<int>>& descriptions) {
unordered_map<int, TreeNode*> m;
unordered_set<int> vis;
for (auto& d : descriptions) {
int p = d[0], c = d[1], left = d[2];
if (!m.count(p)) m[p] = new TreeNode(p);
if (!m.count(c)) m[c] = new TreeNode(c);
if (left)
m[p]->left = m[c];
else
m[p]->right = m[c];
vis.insert(c);
}
for (auto& [v, node] : m) {
if (!vis.count(v)) return node;
}
return nullptr;
}
};