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 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
vector< vector<int> > result;
if (root == NULL)
return result;
queue<TreeNode*> q;
q.push(root);
int count = 1;
int level = 0;
vector<int> tmp(0);
while(!q.empty())
{
tmp.clear();
level = 0;
for (int i = 0; i < count; ++i)
{
root = q.front();
q.pop();
tmp.push_back(root->val);
if (root->left != NULL)
{
q.push(root->left);
++level;
}
if (root->right != NULL)
{
q.push(root->right);
++level;
}
}
count = level;
result.push_back(tmp);
}
return result;
}
};
1万+




被折叠的 条评论
为什么被折叠?



