-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbfs.cpp
157 lines (130 loc) · 3.25 KB
/
bfs.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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#include<iostream>
#include<algorithm>
using namespace std;
class TreeNode
{
private:
TreeNode(int x){
data = x;
left = NULL;
right = NULL;
}
TreeNode *left;
TreeNode *right;
int data;
int level;
friend class Tree;
};
class Node
{
public:
Node(TreeNode *n)
{
node = n;
next = NULL;
}
private:
Node *next;
TreeNode *node;
friend class Queue;
};
class Queue
{
public:
Queue()
{
head = tail = NULL;
}
bool empty()
{
if(!head)
return true;
return false;
}
void enqueue(TreeNode *node)
{
Node *p = new Node(node);
if(tail)
tail->next = p;
else
head = p;
tail = p;
}
TreeNode * dequeue()
{
if(empty())
return NULL;
Node *p = head;
TreeNode *node = p->node;
head = head->next;
delete p;
if(!head)
tail = NULL;
return node;
}
private:
Node *head, *tail;
};
class Tree{
public:
Tree(){
root = NULL;
}
void insertParen(string input){
if(!root){
int index = 0;
root = insertParenHelper(input,index,root);
}
}
void bfs(){
if(!root){
return;
}
Queue queue;
queue.enqueue(root);
root->level = 0;
TreeNode *curr;
while(curr=queue.dequeue()){
cout<<curr->data<<" "<<curr->level<<endl;
if(curr->left){
queue.enqueue(curr->left);
curr->left->level = curr->level+1;
}
if(curr->right){
queue.enqueue(curr->right);
curr->right->level = curr->level+1;
}
}
}
private:
TreeNode *root;
TreeNode* insertParenHelper(string input, int &index, TreeNode *tree){
index++;
if(index==input.length()||input[index]==41)
return NULL;
int data = 0;
bool negative = false;
if(input[index]==45)
{
index++;
negative = true;
}
while(input[index]>=48 && input[index]<=57){
data = data*10 + (input[index]-48);
index++;
}
data = negative? -data : data;
tree = new TreeNode(data);
tree->left = insertParenHelper(input,index,tree->left);
index++;
tree->right = insertParenHelper(input,index,tree->right);
index++;
return tree;
}
};
int main(){
Tree tree;
string input = "(43(60(82()(70()()))(50()()))(15(30(35()())(20()()))(8()())))";
tree.insertParen(input);
tree.bfs();
}