【打卡第238道】【二叉树】【leetCode高频】:513. 找树左下角的值

1、题目描述

给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。

假设二叉树中至少有一个节点。

2、算法分析

这题可以使用BFS,也就是层次遍历。

思路如下:

使用队列对二叉树进行层次遍历,注意最关键的是找到最后一层,当count(层次遍历的深度)等于二叉树的最大深度的时候,队列中出队的第一个元素就是最底层,最左边的元素值。

看代码注释详细:

3、代码实现

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int findBottomLeftValue(TreeNode root) {
        if(root.left == null && root.right == null){
            return root.val;
        }
        // 入队root
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        // 定义深度为1,层次遍历一层,深度加一层。
        int count = 1;
        // 找到二叉树的最大深度
        int max = maxHeight(root);
        // 定义结果结点值
        TreeNode leftVal = null;
        // 遍历队列
        while(!queue.isEmpty()){
            // 队列大小
            int size = queue.size();
            // 每一层深度+1
            ++count;
            // 遍历这一层,下一层的元素入队
            for(int i = 0;i < size;i++){
                // 注意这儿是出队的。
                TreeNode node = queue.poll();
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
            }
            // 每一层遍历,判断深度是否为二叉树的高度最大值
            if(count == max){
                leftVal = queue.poll(); 
            }
        }
        // 返回。
        return leftVal.val;
    }
    public int maxHeight(TreeNode root){
        if(root == null){
            return 0;
        }
        return Math.max(maxHeight(root.left),maxHeight(root.right)) + 1;
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值