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] ]
题目要求对二叉树进行层次遍历,代码如下:
class Solution
{
public:
vector<vector<int> > levelOrder(TreeNode *root)
{
vector<vector<int>>result;
if (!root)
return result;
queue<TreeNode*> vec;
vec.push(root);
while (vec.size() > 0) {
queue<TreeNode*> tmp_vec;
vector<int> tmp_result;
while (vec.size() > 0) {
TreeNode* node = vec.front();
vec.pop();
if (node->left)
tmp_vec.push(node->left);
if (node->right)
tmp_vec.push(node->right);
tmp_result.push_back(node->val);
}
vec = tmp_vec;
result.push_back(tmp_result);
}
return result;
}
};