Skip to content

Commit aa75c52

Browse files
authored
Create main.cpp
1 parent 6963674 commit aa75c52

File tree

1 file changed

+80
-0
lines changed
  • 17 - Binary Tree Data Structure Problems/32 - Buring Tree

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
class Solution {
2+
public:
3+
Node* createParentMapping(Node* root, int target, unordered_map<Node*, Node*>&nodeToParent){
4+
Node* result = NULL;
5+
queue<Node*> q;
6+
q.push(root);
7+
8+
nodeToParent[root] = NULL;
9+
10+
while(!q.empty()){
11+
Node* front = q.front();
12+
q.pop();
13+
14+
if(front -> data == target) result = front;
15+
16+
if(front -> left){
17+
nodeToParent[front -> left] = front;
18+
q.push(front -> left);
19+
}
20+
21+
if(front -> right){
22+
nodeToParent[front -> right] = front;
23+
q.push(front -> right);
24+
}
25+
}
26+
27+
return result;
28+
}
29+
30+
int burnTree(Node* root, unordered_map<Node*, Node*> &nodeToParent){
31+
unordered_map<Node*, bool> visited;
32+
queue<Node*> q;
33+
34+
q.push(root);
35+
visited[root] = true;
36+
37+
int ans = 0;
38+
39+
while(!q.empty()){
40+
bool flag = false;
41+
int size = q.size();
42+
43+
for(int i = 0; i < size; i++){
44+
Node* front = q.front();
45+
q.pop();
46+
47+
if(front -> left && !visited[front->left]){
48+
flag = true;
49+
q.push(front -> left);
50+
visited[front -> left] = true;
51+
}
52+
53+
if(front -> right && !visited[front -> right]){
54+
flag = true;
55+
q.push(front -> right);
56+
visited[front -> right] = true;
57+
}
58+
59+
if(nodeToParent[front] && !visited[nodeToParent[front]]){
60+
flag = true;
61+
q.push(nodeToParent[front]);
62+
visited[nodeToParent[front]] = true;
63+
}
64+
}
65+
66+
if(flag == true) ans++;
67+
68+
}
69+
70+
return ans;
71+
}
72+
73+
int minTime(Node* root, int target)
74+
{
75+
unordered_map<Node*, Node*> nodeToParent;
76+
Node* targetNode = createParentMapping(root, target, nodeToParent);
77+
78+
return burnTree(targetNode, nodeToParent);
79+
}
80+
};

0 commit comments

Comments
 (0)