LeetCode.513 Find Bottom Left Tree Value

本文介绍了一种有效的方法来找到给定二叉树中最底层最左侧叶子节点的值,通过两种不同的实现思路进行讲解:一种是基于递归深度比较的方式,另一种则是利用递归遍历并记录最大深度的节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

Given a binary tree, find the leftmost value in the last row of the tree.

Example 1:

Input:

    2
   / \
  1   3

Output:
1

Example 2:

Input:

        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7

Output:
7

Note:You may assume the tree (i.e., the given root node) is not NULL.

分析(原创):

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int findBottomLeftValue(TreeNode root) {
        //给定二叉树,找出最下一层最左边的叶子结点的值。
        //思路:根据左右子树的depth来判定最深的叶子节点
        if(root.left==null&&root.right==null){
            return root.val;
        }
        if(depth(root.left)>=depth(root.right)){
            return findBottomLeftValue(root.left);
        }else if(depth(root.left)<depth(root.right)){
            return findBottomLeftValue(root.right);
        }
        return root.val;
        
    }
    public int depth(TreeNode root){
        if(root==null) return 0;
        int right=depth(root.right)+1;
        int left=depth(root.left)+1;
        return Math.max(right,left);
    }
}

分析2(参考答案):

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int deep=0;
    public int res=0;
    public int findBottomLeftValue(TreeNode root) {
        //给定二叉树,找出最下一层最左边的叶子结点的值。
        //思路:定义公共变量,来记录当前是否大于depth,同时记录res结果
        backtrace(root,1);
        return res;
    }
    public void backtrace(TreeNode root,int depth){
        if(root!=null){
            if(deep<depth){
                deep=depth;
                res=root.val;
            }
            //递归左右孩子,因为同一层的总是先遍历left
            backtrace(root.left,depth+1);
            backtrace(root.right,depth+1);
        }
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值