「优选算法刷题」:在每个树行中找最大值

59 阅读1分钟

一、题目

给定一棵二叉树的根节点 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

二、思路解析

对二叉树熟悉的朋友应该一看就清楚,这道题用的是宽度优先搜索(BFS)。通过逐层遍历二叉树,去每一层中找到最大值。

在遍历过程中,我们通过一个 tmp 变量来记录每一层的最大值。

具体实现是,先比较当前节点和 tmp 的值,然后更新 tmp 的值为这两数之间的较大值。

这一层走完,我们就要去到下一层,当然前提是有下一层。

最后把每一层的最大值添加到结果列表即可。

三、完整代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if(root == null){
            return ret;
        }
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);

        while(!q.isEmpty()){
            int sz = q.size();
            int tmp = Integer.MIN_VALUE;
            for(int i = 0; i < sz; i++){
                TreeNode t = q.poll();
                tmp = Math.max(tmp, t.val);
                if(t.left != null){
                    q.add(t.left);
                }
                if(t.right != null){
                    q.add(t.right);
                }
            }
            ret.add(tmp);
        }
        return ret;
    }
}

以上就是本篇博客的全部内容啦,如有不足之处,还请各位指出,期待能和各位一起进步!