给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[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>> res_all;
queue<TreeNode*> this_level;
TreeNode* p;
if (root)
this_level.push(root);
while (!this_level.empty())
{
vector<int> res_level;
queue<TreeNode*> next_level;
while (!this_level.empty())
{
p = this_level.front();
this_level.pop();
res_level.push_back(p->val);
if (p->left)
next_level.push(p->left);
if (p->right)
next_level.push(p->right);
}
res_all.push_back(res_level);
this_level = next_level;
}
return res_all;
}
};