题目描述
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。

C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
//思路:设置一个变量Depth,标记每个节点所在的层,走到每一层,还没有申请空间就申请空间,已经申请空间了就直接追加到这一层的向量中。
class Solution {
public:
vector<vector<int>> res;
//因为左右子树的相同层,需要添加到同一个子列表,所以设置成成员变量比较好
vector<vector<int>> levelOrder(TreeNode* root) {
if(!root) return res;
pre(root,0);
return res;
}
void pre(TreeNode *root,int depth)
{
if(!root) return;
if(depth>=res.size()){ //说明是第一次来这一层,就得申请空间
res.push_back(vector<int>{});
}
res[depth].push_back(root->val);
pre(root->left,depth+1);
pre(root->right,depth+1);
}
};

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



