描述

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

示例

示例1:

  1. 输入: root = [1,3,2,5,3,null,9]
  2. 输出: [1,3,9]
  3. 解释:
  4. 1
  5. / \
  6. 3 2
  7. / \ \
  8. 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

解题思路

这道题的关键点是:层序遍历,如何确保遍历的节点是同一层的。
我们用一个变量 size 保存当前 queue 的长度,然后用 for 循环遍历 queue 中所有元素,统计最大值,将子节点加入节点。然后更新 size, 重复执行这个操作,知道 queue 为空。这样就能保证每个 for 循环中遍历的节点是同一层的。

代码

/**
 * 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> res = new ArrayList<Integer>();
        if (root == null) return res;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int max = Integer.MIN_VALUE;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode cur = queue.poll();
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
                max = Math.max(max, cur.val);
            }
            res.add(max); 
        }
        return res;
    }
}

复杂度分析

时间复杂度:O(n)
空间复杂度:O(n)