Skip to content

Commit 3c9c556

Browse files
committed
Create Binary Tree Level Order Traversal.cpp
1 parent 61cba75 commit 3c9c556

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Binary Tree Level Order Traversal.cpp

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* Definition for binary tree
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
vector<vector<int> > levelOrder(TreeNode *root) {
13+
// Start typing your C/C++ solution below
14+
// DO NOT write int main() function
15+
if (!root)return vector<vector<int> >();
16+
queue<TreeNode *>q;
17+
q.push(root);
18+
int node_in_now_level=1;
19+
int node_in_next_level=0;
20+
vector<vector<int> >ans;
21+
vector<int>now;
22+
while (!q.empty())
23+
{
24+
TreeNode *p=q.front();
25+
q.pop();
26+
now.push_back(p->val);
27+
node_in_now_level--;
28+
if (p->left)
29+
{
30+
q.push(p->left);
31+
node_in_next_level++;
32+
}
33+
if (p->right)
34+
{
35+
q.push(p->right);
36+
node_in_next_level++;
37+
}
38+
if (!node_in_now_level)
39+
{
40+
ans.push_back(now);
41+
now.clear();
42+
swap(node_in_now_level,node_in_next_level);
43+
}
44+
}
45+
return ans;
46+
}
47+
};

0 commit comments

Comments
 (0)