代码随想录——找树左下角的值(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;
    }
}
相关推荐
钱六两9 分钟前
#3、SpringAI 接入deepSeek大模型(喂饭版)
java·spring boot·ai编程
ChaoZiLL1 小时前
我的数据结构4-栈和队列
数据结构
香辣牛肉饭1 小时前
【算法】动态规划 最长公共子序列(LCS)
经验分享·笔记·算法·动态规划
miller-tsunami1 小时前
顺序表相关知识点
数据结构·顺序表
null_171 小时前
IntelliJ IDEA 极致流畅配置方案:Ultra 9 285K + 64GB 内存实测
java·ide·intellij-idea
Herbert_hwt1 小时前
建立Java程序开发
java·开发语言
好好沉淀2 小时前
@ExcelIgnoreUnannotated 和 @AutoMapper 详解
java
愚公移码2 小时前
蓝凌EKP18产品:流程虚拟机(PVM)
java·开发语言·前端
.徐十三.2 小时前
一篇文章看到最短路径——Dijkstra算法
算法