zoukankan      html  css  js  c++  java
  • 刷题-力扣-515. 在每个树行中找最大值

    515. 在每个树行中找最大值

    题目链接

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    题目描述

    给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。

    示例1:

    输入: root = [1,3,2,5,3,null,9]
    输出: [1,3,9]
    解释:
              1
             / 
            3   2
           /      
          5   3   9 
    

    示例2:

    输入: root = [1,2,3]
    输出: [1,3]
    解释:
              1
             / 
            2   3
    

    示例3:

    输入: root = [1]
    输出: [1]
    

    示例4:

    输入: root = [1,null,2]
    输出: [1,2]
    解释:      
               1 
                
                 2     
    

    示例5:

    输入: root = []
    输出: []
    

    提示:

    • 二叉树的节点个数的范围是 [0,104]
    • -231 <= Node.val <= 231 - 1

    题目分析

    1. 根据题目描述获取树中每一层的最大值
    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:
        vector<int> largestValues(TreeNode* root) {
            vector<int> res;
            if (!root) return res;
            queue<TreeNode*> nodeList;
            nodeList.emplace(root);
            while (!nodeList.empty()) {
                int max = nodeList.front()->val;
                int nodeListLen = nodeList.size();
                for (int i = 0; i < nodeListLen; ++i) {
                    max = max > nodeList.front()->val ? max : nodeList.front()->val;
                    if (nodeList.front()->left) nodeList.emplace(nodeList.front()->left);
                    if (nodeList.front()->right) nodeList.emplace(nodeList.front()->right);
                    nodeList.pop();
                }
                res.emplace_back(max);
            }
            return res;
        }
    };
    
  • 相关阅读:
    Mysql创建自定义函数
    本草纲目之五味四气
    linux svn命令
    linux命令提升
    php isset缺陷 用array_key_exists
    jquery之ajax
    简单的小游戏(猜数字)
    小球上下左右移动
    如果想在输出面板中排列出一个乘法口诀表请用以下方法
    并联电路
  • 原文地址:https://www.cnblogs.com/HanYG/p/15155460.html
Copyright © 2011-2022 走看看