首页 > 其他分享 >107.binary-tree-level-order-traversal-ii 二叉树的层序遍历II

107.binary-tree-level-order-traversal-ii 二叉树的层序遍历II

时间:2022-08-20 21:35:32浏览次数:108  
标签:node binary level int res 二叉树 push size

参考102.binary-tree-level-order-traversal 二叉树的层序遍历,翻转一下结果数组就好了。

class Solution {
  public:
    vector<vector<int>> levelOrderBottom(TreeNode *root) {
        queue<TreeNode *> q;
        vector<vector<int>> res;
        int depth = 0;
        if (root != nullptr)
            q.push(root);
        while (!q.empty()) {
            vector<int> temp;
            int size = q.size();
            // 如何识别节点在同一层?利用queue的size()来进行处理。
            for (int i = 0; i < size; i++) {
                TreeNode *node = q.front();
                q.pop();
                temp.push_back(node->val);
                if (node->left != nullptr)
                    q.push(node->left);
                if (node->right != nullptr)
                    q.push(node->right);
            }
            res.push_back(temp);
        }
        std::reverse(res.begin(), res.end());
        return res;
    }
};

标签:node,binary,level,int,res,二叉树,push,size
From: https://www.cnblogs.com/zwyyy456/p/16608665.html

相关文章

  • 【数据结构】红黑树与平衡二叉树的区别以及原理详解(附图解)
    引用网址:https://blog.csdn.net/weixin_44780082/article/details/112239269文章目录前言一、什么是红黑树1.1平衡二叉树1.2红黑树1.3平衡二叉树和红黑树的区别二、红黑......
  • Binary Classification
    给定m个样本,根据每个样本拥有的n个特征对它们分类。最基础的分类问题是BinaryClassification,输出结果为Yes或No。Logisticregression相较于线性回归假设因......
  • 二叉树的统一迭代法遍历
    中序遍历中序遍历无法直接利用栈进行遍历,需要利用指针进行遍历,对栈中的节点进行操作。对于中间节点,如果指针遍历到了,但没有进行处理,就再push()一个nullptr,作为标记,说明这......
  • 二叉树 查找第k大的数
    改造方法需在节点N中记录以节点N为根的子树的节点数numOfNodes,根节点记录整颗树的节点数目,则若根节点的左子树的numOfNodes刚好为k-1,那这个根节点的值即为目标值。注意......
  • 2022-8-20 每日一题-二叉树-递归
    654.最大二叉树难度中等499收藏分享切换为英文接收动态反馈给定一个不重复的整数数组 nums 。 最大二叉树 可以用下面的算法从 nums 递归地构建:创建一个......
  • [Google] LeetCode 366 Find Leaves of Binary Tree
    Giventherootofabinarytree,collectatree'snodesasifyouweredoingthis:Collectalltheleafnodes.Removealltheleafnodes.Repeatuntilthetre......
  • [Google] LeetCode 2096 Step-By-Step Directions From a Binary Tree Node to Anothe
    Youaregiventherootofabinarytreewithnnodes.Eachnodeisuniquelyassignedavaluefrom1ton.YouarealsogivenanintegerstartValuerepresenting......
  • 654. 最大二叉树
    654.最大二叉树给定一个不重复的整数数组 nums。 最大二叉树 可以用下面的算法从 nums递归地构建:创建一个根节点,其值为 nums中的最大值。递归地在最大值......
  • LeetCode/最大二叉树
    给定一个不重复的整数数组nums。最大二叉树可以用下面的算法从nums递归地构建:创建一个根节点,其值为nums中的最大值递归地在最大值左边的子数组前缀上构建......
  • 【LeetCode】102.二叉树的层序遍历
    【LeetCode】102.二叉树的层序遍历/**转载请说明出处与作者*作者:多巴胺dopamine*/一问题描述1题目给你二叉树的根节点root,返回其节点值的层序遍历。(即......