-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCreate-Binary-Tree-From-Descriptions.cpp
More file actions
87 lines (77 loc) · 2.22 KB
/
Create-Binary-Tree-From-Descriptions.cpp
File metadata and controls
87 lines (77 loc) · 2.22 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* 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) {}
* };
*/
#include <deque>
#include <unordered_map>
#include <vector>
using namespace std;
class Solution
{
public:
void DFS(TreeNode *root, unordered_map<int, int> left, unordered_map<int, int> right)
{
root->left = root->right = NULL;
if (left.count(root->val))
{
root->left = new TreeNode(left[root->val]);
DFS(root->left, left, right);
};
if (right.count(root->val))
{
root->right = new TreeNode(right[root->val]);
DFS(root->right, left, right);
};
return;
};
TreeNode *createBinaryTree(vector<vector<int>> &descriptions)
{
unordered_map<int, int> left, right, notFather;
for (const vector<int> &description : descriptions)
{
int parent = description[0], child = description[1], isLeft = description[2];
notFather[child] = true;
if (isLeft)
left[parent] = child;
else
right[parent] = child;
};
int root = -1;
for (const vector<int> &description : descriptions)
{
int parent = description[0];
if (!notFather[parent])
{
root = parent;
break;
};
};
TreeNode *ro = new TreeNode(root);
deque<TreeNode *> d;
d.push_back(ro);
while (!d.empty())
{
TreeNode *cur = d.front();
d.pop_front();
if (left.count(cur->val))
{
cur->left = new TreeNode(left[cur->val]);
d.push_back(cur->left);
};
if (right.count(cur->val))
{
cur->right = new TreeNode(right[cur->val]);
d.push_back(cur->right);
};
};
// DFS(ro, left, right);
return ro;
}
};