0
点赞
收藏
分享

微信扫一扫

[[EVD]] - 剑指 Offer 32 - II. 从上到下打印二叉树 II

闲嫌咸贤 2022-03-30 阅读 27

题目分析:[[EVD]] - 剑指 Offer 32 - II. 从上到下打印二叉树 IIhttps://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/

简单描述:

  • 二叉树层序打印,每一层一组

限制🚫

  • 节点总数 <= 1000

示例:

解题思路:

思路:

  • #BFS 对输出进行结构化
    • 每次取尽一层,取k次(k为树的高度),而不是通常的一个个取
    • ⚠️二维vector使用 #[[C++ STL]]
      • 没有指定外层vector大小时,使用v[0].push_back(val)会出问题

效率:

  • 时间复杂度O(n)
  • 空间复杂度O(n)

代码:

class Solution
{
public:
    /*简单BFS,对输出结构化,第一层循环取k次(树的高度),第二层循环取尽同一层节点*/
    vector<vector<int> > levelOrder(TreeNode *root)
    {
        queue<TreeNode *> t;
        vector<vector<int> > res;
        if (!root)
            return res;
        t.push(root);
        while (!t.empty())
        {
            vector<int> tmp;
            int tmpI = t.size();    //循环中t队列长度会改变,因此设定一个固定值
            while (tmpI--)
            {
                TreeNode *temp = t.front();
                t.pop();
                tmp.push_back(temp->val);
                if (temp->left)
                    t.push(temp->left);
                if (temp->right)
                    t.push(temp->right);
            }
            res.push_back(tmp);
        }
        return res;
    }
};
举报

相关推荐

0 条评论