Create Binary Tree From Descriptions LeetCode solution in C++

1
class Solution {
2
public:
3
TreeNode *createBinaryTree(vector<vector<int>> &descriptions) {
4
unordered_map<int, TreeNode *> getNode; // to check if node alredy exist
5
unordered_map<int, bool> isChild; // to check if node has parent or not
6
for (auto &v : descriptions) {
7
if (getNode.count(v[0]) == 0) {
8
TreeNode *par = new TreeNode(v[0]);
9
getNode[v[0]] = par;
10
}
11
if (getNode.count(v[1]) == 0) {
12
TreeNode *child = new TreeNode(v[1]);
13
getNode[v[1]] = child;
14
}
15
if (v[2] == 1)
16
getNode[v[0]]->left = getNode[v[1]]; // left-child
17
else
18
getNode[v[0]]->right = getNode[v[1]]; // right-child
19
isChild[v[1]] = true;
20
}
21
TreeNode *ans = NULL;
22
for (auto &v : descriptions) {
23
if (isChild[v[0]] != true) { // if node has no parent then this is root node
24
ans = getNode[v[0]];
25
break;
26
}
27
}
28
return ans;
29
}
30
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0