Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ 9 20
/ 15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
/**
* Definition for a binary tree node.
* 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>> out_vec;
vector<int> vec;
if(root == NULL)
return out_vec;
queue<TreeNode*> que;
que.push(root);
int level = 0;
int num = 1;
while(!que.empty())
{
vec.clear();
level = 0;
for(int i = 0; i < num; i ++)
{
root = que.front();
que.pop();
vec.push_back(root->val);
if(root->left != NULL)
{
que.push(root->left);
level ++;
}
if(root->right != NULL)
{
que.push(root->right);
level ++;
}
}
num = level;
out_vec.push_back(vec);
}
return out_vec;
}
};
【LeetCode】Binary Tree Level Order Traversal(层序遍历)
原文地址:http://blog.csdn.net/zwhlxl/article/details/46622619