代码随想录——找树左下角的值(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;
    }
}
相关推荐
ThsPool1 小时前
【ENVI二次开发学习整理 04】ENVI功能扩展与二次开发
java·前端·javascript
赤壁小虾1 小时前
【渲染流水线】[逐片元阶段]-[透明度测试]以UnityURP为例
java·前端·数据库
Re.不晚1 小时前
挑战做100道力扣算法- DAY1
算法·leetcode·职场和发展
蓝悦无人机2 小时前
《Planning algorithms》读书笔记——第1章 引言
算法·读书笔记·规划算法·lavalle
Sagittarius_A*2 小时前
分组密码基础(二):Feistel 结构与 DES 的设计思想
算法·信息安全·密码学·des·数论
青山木2 小时前
Hot 100 --- 搜索插入位置
java·数据结构·算法·leetcode
Jul1en_2 小时前
【Claude Code Compact】源码级别的学习上下文压缩
java·前端·学习·github·ai编程
XWalnut3 小时前
SpringBoot快速入门
java·spring boot·后端
alexwang2113 小时前
HDU 4348 详细题解
c++·算法·题解·hdu·主席树·可持久化数据结构·可持久化线段树
前端 贾公子3 小时前
第06章:结构化输出 (上)
java·服务器·前端