【leetcode】每日精选题详解之513. 找树左下角的值

        嗨,大家好,我是袁厨(因为酷爱做饭,所以自己考取了厨师证)。之前一直看大家写的博客,学到了很多东西。然后最近萌生了自己写的想法,将自己知道的分享给需要的同学。以后每天会为大家分享leetcode精选题目的各种题解和Python, JS, JQ, CSS, PHP, JAVA的一些小Demo。请大家关注我,一起交流学习吧。


题目描述

在这里插入图片描述


层次遍历(BFS)

做题思路

这个方法比较好想到,也比较容易,但是消耗的时间较多,主要思路就是,根据层次遍历,每次保存每一层的第一个值即可。然后等遍历完之后输出该值

题目代码

class Solution {
    
    
    public int findBottomLeftValue(TreeNode root) {
    
     
        if(root == null){
    
    
            return 0; 
        }
        //创建一个队列,用来保存每一层的数值
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        int leftnum = 0;
        //入栈
        queue.offer(root);
        //循环条件
        while(!queue.isEmpty()){
    
    
            int size = queue.size();
            //获取第一个元素,即我们找到的最左边的元素
            leftnum = queue.element().val;
            for(int i = 0;i < size ; i++){
    
    
                //出队
                TreeNode p = queue.poll();
                TreeNode left = p.left;
                TreeNode right = p.right;
                if(left != null){
    
    
                    queue.offer(left);
                }
                if(right != null){
    
    
                    queue.offer(right);
                }
                
            }
        }
       return leftnum;
   
    }
}

        


递归法

做题思路

我们可以需要定义两个变量,来找到最底层,当达到最底层时,将值赋给 maxlevelvalue也就是我们需要输出的值。
  //用来判断又到达下一层的时候,因为leftlen是会改变的,
  //每下一层则会加1.当下到新的一层时则将最左边的值赋给maxlevelvalue进行输出。
  if(maxlen < leftlen){
    
    
                maxlen = leftlen;
                maxlevelvalue = root.val;
            }

题目代码

class Solution {
    
    
    int maxlen = 0;
    int maxlevelvalue = 0;
    public int findBottomLeftValue(TreeNode root) {
    
    
            if(root == null){
    
    
                return 0;
            }
            dfs(root,1);
            return maxlevelvalue;
       
    }
    public void dfs(TreeNode root,int leftlen){
    
    
        //叶子节点情况
        if(root.left == null && root.right == null){
    
    
          //更新了一层,重新赋值
            if(maxlen < leftlen){
    
    
                maxlen = leftlen;
                maxlevelvalue = root.val;

            }
            return ;
        }
        //左节点
        if(root.left != null){
    
    
            leftlen++;
            dfs(root.left,leftlen);
            //回溯
            leftlen--;
        }
        if(root.right != null){
    
    
            leftlen++;
            dfs(root.right,leftlen);
            leftlen--;
        }
        return ;
    }
}

当然这个代码是可以精简的,但是就显示不出来递归三要素啦,所以为了便于理解,先根据递归三要素理解完之后再精简吧。


总结

同学们我最近有了一个长久的计划,就是把leetcode题目整理出来,由浅入深,由简到繁都整理出来是一个宏大的工程,所以我打算每天整理一到两个经典题目,完成这一个流程我相信肯定会收获巨大的。如果想一起刷题的哥们,我们可以一起在群里打卡,共同进步。

在这里插入图片描述
在这里插入图片描述

作者:LeetCode
链接:https://leetcode-cn.com/problems/rotate-array/solution/xuan-zhuan-shu-zu-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

猜你喜欢

转载自blog.csdn.net/tan45du_yuan/article/details/108968720