代码随想录——找树左下角的值(Leetcode513)

题目链接

层序遍历

思路:使用层序遍历,记录每一行 i = 0 的元素,就可以找到树左下角的值

java 复制代码
/**
 * 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) {
        Deque<TreeNode> queue = new LinkedList<TreeNode>();
        int res = root.val;
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i = 0; i < size; i++){
                TreeNode node = queue.poll();
                if(i == 0){
                    res = node.val;
                }
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
            }
        }
        return res;
    }
}
相关推荐
Scabbards_5 分钟前
面试Leetcode - Heap 堆
java·leetcode·面试
程序员清风41 分钟前
专业再升级!程序员专属显示器明基RD280UG上手实测!
java·后端·面试
(╹◡╹)2 小时前
18.剪枝
算法·机器学习·剪枝
布莱克6052 小时前
数据库索引分类:数据结构、物理存储与逻辑角度详解
数据结构·数据库
Lam Tang2 小时前
APS 系列文章 08
java·代理模式
Fa_Mian_Tuan3 小时前
图论基础|邻接矩阵超详细讲解(含无向/有向/带权图+完整可运行C语言代码)
c语言·数据结构·笔记·算法·图论
hanhahai3 小时前
指针与函数(函数指针与指针函数)
算法
萧瑟余晖3 小时前
Java深入解析篇三十三之消息队列
java·开发语言
码匠许师傅3 小时前
【C++ 面试真题】聊聊 C++ 的序列容器
java·c++·面试
ValhallaCoder3 小时前
Leetcode-hot100(2026.08.17)
python·算法·leetcode