Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[2022-06-24]515. 在每个树行中找最大值👋树👋深度优先搜索👋广度优先搜索👋二叉树 #78

Open
webVueBlog opened this issue Jun 24, 2022 · 1 comment

Comments

@webVueBlog
Copy link
Member

题目链接: https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row

难度: Medium
标签: 深度优先搜索 广度优先搜索 二叉树

@dreamjean
Copy link
Collaborator

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

Description

Difficulty: 中等

Related Topics: , 深度优先搜索, 广度优先搜索, 二叉树

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

示例1:

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

示例2:

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

提示:

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

Solution

Language: JavaScript

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var largestValues = function(root) {
     if (!root) return [];

    const queue = [root];   
    const res = [];

    while (queue.length) {
        const size = queue.length;
        let max = -Infinity;
        for (let i = 0; i < size; i++) {
            const { val, left, right } = queue.shift();
            max = Math.max(max, val);

            if (left) queue.push(left);
            if (right) queue.push(right);
        }
       
        res.push(max);
    }
    
    return res;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants