515-Find Largest Value in Each Tree Row

本文介绍了一种算法问题:如何找到二叉树每一层的最大值。通过两种不同的实现方式,即广度优先搜索(BFS)和深度优先搜索(DFS),详细解释了其解决方案。这两种方法都能有效地解决问题,并提供了清晰的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

You need to find the largest value in each row of a binary tree.


Example:

Input: 

          1
         / \
        3   2
       / \   \  
      5   3   9 

Output: [1, 3, 9]

问题描述

找出二叉树每层中最大的值


问题分析

前序遍历, 注意利用高度


解法1

class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> res = new ArrayList();
        if (root == null) return res;

        Queue<TreeNode> queue = new LinkedList();
        queue.add(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            int max = Integer.MIN_VALUE;
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                max = Math.max(max, node.val);
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
            res.add(max);
        }

        return res;
    }
}

解法2

class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> res = new ArrayList();
        if(root == null) return res;

        find(root, res, 0);

        return res;
    }
    public void find(TreeNode root, List<Integer> res, int depth){
        if(root == null) return;

        if(depth >= res.size()) res.add(root.val);
        else if(res.get(depth) < root.val) res.set(depth, root.val);
        find(root.left, res, depth + 1);
        find(root.right, res, depth + 1);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值