剑指Offer || 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 = []
输出: []

提示:

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

注意:本题与主站 515 题相同: 力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

LCR 044. 在每个树行中找最大值 - 力扣(LeetCode)

题解

思路一:DFS,用先序遍历深搜,并用 curHeight来标记遍历到的当前节点的高度。当遍历到 时判断是否更新该层节点的最大值。

代码:

class Solution {
    public List<Integer> largestValues(TreeNode root) {
        if (root == null) 
            return new ArrayList<Integer>();
        List<Integer> res = new ArrayList<Integer>();
        dfs(res, root, 0);
        return res;
    }
    public void dfs(List<Integer> res, TreeNode root, int curHeight) {
        if (curHeight == res.size()) //到新的一层,加进来第一个值
            res.add(root.val);
         else 
            res.set(curHeight, Math.max(res.get(curHeight), root.val));
        if (root.left != null) 
            dfs(res, root.left, curHeight + 1);
        if (root.right != null) 
            dfs(res, root.right, curHeight + 1);
    }
}

思路二:BFS,层序遍历,一层一层扩展,用 maxVal来标记该层节点的最大值。当前层处理完成之后,maxVal即为当前层的最大值。

代码:

class Solution {
    public List<Integer> largestValues(TreeNode root) {
        if (root == null) 
            return new ArrayList<Integer>();
        List<Integer> res = new ArrayList<Integer>();
        Queue<TreeNode> queue = new ArrayDeque<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int len = queue.size();//当前len确保了len--到0时,刚好处理完当前层
            int maxVal = Integer.MIN_VALUE;
            while (len > 0) {
                TreeNode t = queue.poll();
                len--;
                maxVal = Math.max(maxVal, t.val);
                if (t.left != null) 
                    queue.offer(t.left);
                if (t.right != null) 
                    queue.offer(t.right);
            }
            res.add(maxVal);
        }
        return res;
    }
}

tips:关于值传递和引用传递。在Java中用的是值传递。在其它方法里面改变引用类型的值都是通过引用改变的,当传递引用对象的时候,传递的是复制的引用的对象句柄,是复制过的,也就是在内存中复制了一个句柄,这两个句柄指向同一个对象,所以改变这个句柄对应的空间的数据会影响到外部的变量虽然是复制的,但是指向的是同一个地址,当你把这个句柄指向其它对象的引用时并不会改变原来的值(例如String),因为用的是复制过的句柄。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值