LeetCode-Find Bottom Left Tree Value

本文探讨了在二叉树中查找最后一行最左侧节点值的两种方法:一是利用层次遍历结合高度计算,二是使用递归并跟踪层级。通过具体示例和代码实现,深入解析算法原理。

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

一、Description

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

二、Analyzation

这里提供两种思路:

1.先求出二叉树的高度,然后通过层次遍历,等到遍历到最后一行时,直接返回此时队列中的第一个结点即为所求,见代码一。

2.在递归函数的参数列表中加入一个level,在递归遍历的同时level加一,如果在同一层,那么首先递归返回的一定是该层最左边的结点(根据递归顺序),因此最后的left即为所求。


三、Accepted code

代码一:

class Solution {
    public int findBottomLeftValue(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        int h = height(root);
        int val = 0, size = 0;
        queue.add(root);
        while (!queue.isEmpty()) {
           h--;
            if (h == 0) {
                val = queue.poll().val;
                break;
            }
            size = queue.size();
            while (size > 0) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
                size--;
            }
        }
        return val;
    }
    public int height(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        int leftHeight = 0, rightHeight = 0;
        if (root.left != null) {
            leftHeight = height(root.left) + 1;
        }
        if (root.right != null) {
            rightHeight = height(root.right) + 1;
        }
        return leftHeight > rightHeight ? leftHeight : rightHeight;
    }
}

代码二:

class Solution {
    int left = 0;
    int preLevel = 0;
    
    public int findBottomLeftValue(TreeNode root) {
        left = root.val;
        help(root, 0);
        return left;
    }
    
    public void help(TreeNode root, int level) {
        if(root.left != null) {
            help(root.left, level + 1);
        }
        if(root.right != null) {
            help(root.right, level + 1);
        }
        if(level > preLevel) {
            left = root.val;
            preLevel = level;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值