剑指 Offer II 044. 二叉树每层的最大值

168 阅读2分钟

「这是我参与11月更文挑战的第13天,活动详情查看:2021最后一次更文挑战

剑指 Offer II 044. 二叉树每层的最大值

给定一棵二叉树的根节点 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 = []
输出: []


来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/hPov7L

思路

  • 首先我们思考,如果简单的层序遍历
    • 那么会导致分不清具体的层数

    • 所以我们直观的去思考就是增加变量,来控制当前层是否遍历完

    • 接下来还有保存每层最大节点的问题

  • 根据以上的分析,我们来具体去思考
    • 首先我们有cur来记录当前层的节点在队列中的个数

    • cur0的时候,就代表当前层的节点已经遍历完,这是可以将最大值添加到res结果集中

    • next是代表子节点在队列中的个数,所以当cur0的时候,cur的值置为next

    • 根据两个变量我们完美的控制了来求每层最大节点的思路~

/**
 * 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<>();
            Queue<TreeNode> q = new LinkedList<>();
            int cur = 0;
            int next = 0;
            if (root == null) return res;
            q.offer(root);
            cur = 1;
            int max = Integer.MIN_VALUE;
            while (!q.isEmpty()) {
                TreeNode node = q.poll();
                cur--;
                max = Math.max(max,node.val);

                if (node.left != null) {
                    q.offer(node.left);
                    next++;
                }
                if (node.right != null) {
                    q.offer(node.right);
                    next++;
                }
                // 当前层的节点都遍历完
                if (cur == 0) {
                    res.add(max);
                    max = Integer.MIN_VALUE;
                    cur = next;
                    next = 0;
                }
            }
            return res;
    }
}