-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Burn_Tree.cpp
143 lines (118 loc) · 3 KB
/
Burn_Tree.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
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#include<iostream>
#include<map>
#include<queue>
using namespace std;
class Node{
public:
int data;
Node* left;
Node* right;
Node(int val)
{
data = val;
left = NULL;
right = NULL;
}
};
void printBT(const std::string& prefix, const Node* node, bool isLeft)
{
if (node != nullptr)
{
std::cout << prefix;
std::cout << (isLeft ? "|--" : "L--");
std::cout << node->data << std::endl;
printBT(prefix + (isLeft ? "| " : " "), node->right, true);
printBT(prefix + (isLeft ? "| " : " "), node->left, false);
}
}
void printBT(const Node* node)
{
printBT("", node, false);
}
void Mapping(Node* root, map<Node*, Node*> &parentNode, map<Node*, bool> &visited)
{
if(root==NULL)
return;
if(root->left==NULL && root->right==NULL)
{
visited[root] = false;
return;
}
visited[root] = false;
if(root->left)
parentNode[root->left] = root;
if(root->right)
parentNode[root->right] = root;
Mapping(root->left,parentNode, visited);
Mapping(root->right,parentNode, visited);
}
Node* FindNode(Node* root, int t)
{
if(root==NULL)
return NULL;
if(root->data==t)
return root;
Node* lt = FindNode(root->left, t);
Node* rt = FindNode(root->right, t);
if(lt!=NULL)
return lt;
if(rt!=NULL)
return rt;
return NULL;
}
int BurnTree(Node* root, int t)
{
map<Node*, Node*> parentNode;
map<Node*, bool> visited;
Mapping(root, parentNode, visited);
parentNode[root] = NULL;
Node* target = FindNode(root, t);
queue<Node*> q;
q.push(target);
visited[target] =1;
bool addition = false;
int time = 0;
while(!q.empty())
{
int size = q.size();
addition = false;
for(int i=0; i<size; i++)
{
Node* frontNode = q.front();
q.pop();
if(frontNode->left!=NULL && visited[frontNode->left]==false)
{
visited[frontNode->left] = true;
q.push(frontNode->left);
addition = true;
}
if(frontNode->right!=NULL && visited[frontNode->right]==false)
{
visited[frontNode->right] = true;
q.push(frontNode->right);
addition = true;
}
if(parentNode[frontNode]!=NULL && visited[parentNode[frontNode]]==false)
{
visited[parentNode[frontNode]] = true;
q.push(parentNode[frontNode]);
addition = true;
}
}
if(addition==true)
{
time++;
}
}
return time;
}
int main()
{
Node* root = new Node(1);
root->right = new Node(2);
root->right->right = new Node(3);
root->right->right->right = new Node(4);
root->right->right->right->right = new Node(5);
cout<<BurnTree(root, 4)<<endl;
return 0;
}