二叉树的层序遍历
给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
/**
* 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) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*>tree_queue;
vector<vector<int>>tree_val;
tree_queue.push(root);
while(!tree_queue.empty())
{
if(root==nullptr)
{
break;
}
vector<int>tree_level;
int n=tree_queue.size();
for(int i=n;i>0;i--)
{
TreeNode*p =tree_queue.front();
tree_queue.pop();
tree_level.push_back(p->val);
if(p->left!=nullptr)
{
tree_queue.push(p->left);
}
if(p->right!=nullptr)
{
tree_queue.push(p->right);
}
}
tree_val.push_back(tree_level);
}
return tree_val;
}
};
这里是引用
每次在循环结束前记录父节点左右孩子放入队列中的个数。在下次循环开始时,按上次统计的个数循环,并依次放入level中。
解法2 :递归实现
/**
* 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) {}
* };
*/
class Solution {
public:
void order(TreeNode*root,int depth,vector<vector<int>>&res)
{
if(root==nullptr){return ;}
if(depth==res.size()){
res.push_back(vector<int>());
}
res[depth].push_back(root->val);
order(root->left,depth+1,res);
order(root->right,depth+1,res);
}
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>>res;
if(root==nullptr)
{
return vector<vector<int>>();
}
int depth=0;
order(root,depth,res);
return res;
}
};