-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBinaryTreeLevelOrderTraversal.cpp
More file actions
100 lines (84 loc) · 2.35 KB
/
Copy pathBinaryTreeLevelOrderTraversal.cpp
File metadata and controls
100 lines (84 loc) · 2.35 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
88
89
90
91
92
93
94
95
96
97
98
99
100
/**
Definition for binary tree
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
/* vector<vector<int> > output;
if (!root)
return output;
vector<TreeNode*> list;
list.push_back(root);
TreeNode *pLeftFirt = NULL, *tmp = NULL;
if (root->left)
pLeftFirt = root->left;
else if (root->right)
pLeftFirt = root->right;
while(!list.empty())
{
vector<int> leveloutput;
while (!list.empty() && list.front() != pLeftFirt)
{
tmp = list.front();
list.erase(list.begin());
if (!pLeftFirt)
{
if (tmp->left)
pLeftFirt = tmp->left;
else if (tmp->right)
pLeftFirt = tmp->right;
}
if (tmp->left)
list.push_back(tmp->left);
if (tmp->right)
list.push_back(tmp->right);
leveloutput.push_back(tmp->val);
}
if (list.front()->left)
pLeftFirt = list.front()->left;
else if(list.front()->right)
pLeftFirt = list.front()->right;
else
pLeftFirt = NULL;
output.push_back(leveloutput);
}
return output;
*/
vector< vector<int> > output;
if(!root)
return output;
queue<TreeNode*> list;
list.push_back(root);
list.push(NULL);
vector<int> level;
TreeNode *tmp;
while(!list.empty())
{
tmp = list.front();
list.erase(list.begin());
if (tmp)
{
level.push(tmp->val);
if (tmp->left)
list.push(tmp->left);
if (tmp->right)
list.push(tmp->right);
}
else
{
output.push_back(level);
if (!list.empty()){
level.clear();
list.push(NULL);
}
}
}
return output;
}
};