01.12

本文介绍了两种方法解决找二叉树中最小左下角值的问题:一种是使用层序遍历,通过队列动态更新最小值;另一种是深度优先搜索,利用前序遍历策略确保找到最大深度的左下角值。
摘要由CSDN通过智能技术生成

513.找左下角的值

思路

1.层序遍历做这题比较好做,定义一个变量值为根节点值,后续每循环一层,将值更改为队列的peek值。最后输出。

2.还有一种深搜递归,设置两个全局变量,一个用于记录当前的值,一个用于记录该值在树的层数。深搜遍历采用前序遍历,若深度大于该值,则替换,这样一来会记录深度最大的值,由于采用前序遍历,第一个深度最大的值一定为最左边的值,后续深度相同的值无法替换。

代码

1.层序

class Solution {
    public int findBottomLeftValue(TreeNode root) {
        Queue<TreeNode> queue=new ArrayDeque<>();
        queue.offer(root);
        int size=queue.size();
        int minleft=root.val;
        while (!queue.isEmpty()){
            while (size>0){
                TreeNode node=queue.poll();
                if (node.left!=null) queue.offer(node.left);
                if (node.right!=null) queue.offer(node.right);
                size--;
            }
            size=queue.size();
            if (queue.peek() != null) {
                minleft=queue.peek().val;
            }
        }
        return minleft;
    }
}

2.深搜

    int minleft,max=0;
    public int findBottomLeftValue(TreeNode root) {
        getMinleft(root,1);
        return minleft;
    }

    public void getMinleft(TreeNode root,int depth) {
        if (root==null) return ;
        if (depth>max) {
            minleft=root.val;
            max=depth;
        }
        getMinleft(root.left,depth+1);
        getMinleft(root.right,depth+1);
        return;
    }
  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值