forked from daizhenyang/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary Tree Level Order Traversal.cpp
More file actions
47 lines (47 loc) · 1.19 KB
/
Binary Tree Level Order Traversal.cpp
File metadata and controls
47 lines (47 loc) · 1.19 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:
vector<vector<int> > levelOrder(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!root)return vector<vector<int> >();
queue<TreeNode *>q;
q.push(root);
int node_in_now_level=1;
int node_in_next_level=0;
vector<vector<int> >ans;
vector<int>now;
while (!q.empty())
{
TreeNode *p=q.front();
q.pop();
now.push_back(p->val);
node_in_now_level--;
if (p->left)
{
q.push(p->left);
node_in_next_level++;
}
if (p->right)
{
q.push(p->right);
node_in_next_level++;
}
if (!node_in_now_level)
{
ans.push_back(now);
now.clear();
swap(node_in_now_level,node_in_next_level);
}
}
return ans;
}
};