[C/C++]LeetCode 简单篇之二叉树的层次遍历 II

思路

1.利用数列queue完成每一层的划分
2.利用动态数组vector的 insert() 完成倒序

代码详细解释

class Solution 
{
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root)
    {
        vector<vector<int>> res;//返回值
        if (root==NULL)
            return res;
        
        queue<TreeNode*> q;//存放节点的数列
        q.push(root);//存放根节点
        
        while (!q.empty())
        {
            int l = q.size();//数列的长度
            vector<int> temp; //数组变量
            
            for (int i=0; i<l; i++)
            {
                TreeNode* now = q.front();//复制第一个节点
                q.pop();//第一个节点出数列
                temp.push_back(now->val);
                if (now->left) //如果now的子节点非空,把它按从左到右的顺序放入数列
                    q.push(now->left);
                if (now->right) 
                    q.push(now->right);
            }
            res.insert(res.begin(),temp);//插到第一个数组元素的前面
        }
       
        return res;
    }
};

补充题目

给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

例如:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其自底向上的层次遍历为:

[
  [15,7],
  [9,20],
  [3]
]
发布了43 篇原创文章 · 获赞 80 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_43868654/article/details/96426861