[LeetCode] Create Binary Tree From Descriptions

2196. Create Binary Tree From Descriptions

You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore,

  • If isLefti == 1, then childi is the left child of parenti.
  • If isLefti == 0, then childi is the right child of parenti.

Construct the binary tree described by descriptions and return its root.

The test cases will be generated such that the binary tree is valid.

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
33
34
35
36
37
38
39
40
41
/**
* 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*> node;
unordered_set<int> child;
for(auto desc : descriptions) {
int p = desc[0];
int me = desc[1];
bool left = desc[2];
child.insert(me);
if(!node.count(p)) {
node[p] = new TreeNode(p);
}
if(!node.count(me)) {
node[me] = new TreeNode(me);
}
if(left) {
node[p]->left = node[me];
} else {
node[p]->right = node[me];
}
}

for(auto [val, n]: node) {
if(child.count(val)) continue;
return n;
}
return nullptr;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/06/PS/LeetCode/create-binary-tree-from-descriptions/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.