-
Notifications
You must be signed in to change notification settings - Fork 3
/
binary-tree-level-order-traversal.cpp
98 lines (75 loc) · 2.09 KB
/
binary-tree-level-order-traversal.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
//Runtime: 9 ms
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int> > res;
if(root == NULL)
return res;
queue<pair<int,TreeNode* > >Q;
Q.push(make_pair(0,root));
vector<int> lvl[1000];
lvl[0].push_back(root->val);
int maxlevel = 1;
int f = 1;
while(!Q.empty())
{
pair<int, TreeNode*> t = Q.front();
Q.pop();
if(t.second->left!=NULL)
{
Q.push(make_pair(t.first+1,t.second->left));
lvl[t.first+1].push_back(t.second->left->val);
maxlevel++;
f = 0;
}
if(t.second->right!=NULL)
{
Q.push(make_pair(t.first+1,t.second->right));
lvl[t.first+1].push_back(t.second->right->val);
if(f)
maxlevel++;
else
f = 1;
}
}
for(int i=0;i<1000;i++)
if(lvl[i].size() > 0)
res.push_back(lvl[i]);
return res;
}
};
//Runtime: 3 ms
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int> > res;
if(root == NULL)
return res;
queue<pair<int,TreeNode* > >Q;
Q.push(make_pair(0,root));
int maxlvl = 0;
vector<int>ch;
while(!Q.empty())
{
pair<int, TreeNode*> t = Q.front();
Q.pop();
if(maxlvl < t.first)
{
if(ch.size() > 0)
{
res.push_back(ch);
ch.clear();
}
maxlvl++;
}
ch.push_back(t.second->val);
if(t.second->left!=NULL)
Q.push(make_pair(t.first+1,t.second->left));
if(t.second->right!=NULL)
Q.push(make_pair(t.first+1,t.second->right));
}
if(ch.size() > 0)
res.push_back(ch);
return res;
}
};