forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeLevelOrderTraversal.cpp
More file actions
47 lines (45 loc) · 1.17 KB
/
BinaryTreeLevelOrderTraversal.cpp
File metadata and controls
47 lines (45 loc) · 1.17 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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int BREAK_LINE = -0xffff;
vector<vector<int> > levelOrder(TreeNode *root) {
vector<vector<int> > res;
if(root==NULL) {
return res;
}
TreeNode* nextVec = new TreeNode(BREAK_LINE);
list<TreeNode*> q;
q.push_back(root);
q.push_back(nextVec);
vector<int> thisline;
while(!q.empty()) {
TreeNode* top = q.front();
q.pop_front();
if(top->val == BREAK_LINE) {
res.push_back(thisline);
thisline.clear();
if(q.empty()) {
return res;
}
q.push_back(nextVec);
continue;
}
thisline.push_back(top->val);
if(top->left!=NULL) {
q.push_back(top->left);
}
if(top->right!=NULL) {
q.push_back(top->right);
}
}
return res;
}
};