题目
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,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>> v;
p(root,0,v);
return v;
}
void p(TreeNode* root,int n,vector<vector<int>> &a)
{
if(root==NULL)
return ;
if(n>=a.size())
a.push_back(vector<int> {});
a[n].push_back(root->val);
p(root->left, n + 1,a);
p(root->right, n + 1, a);
}
};
//迭代
/**
* 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>> v;
queue<TreeNode *> q;
if(root==NULL)
return v;
q.push(root);
while(!q.empty())
{
vector<int> tmp;
int len=q.size();
for(int i=0;i<len;i++)
{
TreeNode *p=q.front();
q.pop();
tmp.push_back(p->val);
if(p->left) q.push(p->left);
if(p->right) q.push(p->right);
}
v.push_back(tmp);
}
return v;
}
};