代码随想录——找树左下角的值(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;
    }
}
相关推荐
DCTANT5 分钟前
【原创】国产化适配-全量迁移MySQL数据到OpenGauss数据库
java·数据库·spring boot·mysql·opengauss
Touper.14 分钟前
SpringBoot -- 自动配置原理
java·spring boot·后端
Alfred king17 分钟前
面试150 生命游戏
leetcode·游戏·面试·数组
黄雪超24 分钟前
JVM——函数式语法糖:如何使用Function、Stream来编写函数式程序?
java·开发语言·jvm
ThetaarSofVenice30 分钟前
对象的finalization机制Test
java·开发语言·jvm
水木兰亭36 分钟前
数据结构之——树及树的存储
数据结构·c++·学习·算法
Jess071 小时前
插入排序的简单介绍
数据结构·算法·排序算法
老一岁1 小时前
选择排序算法详解
数据结构·算法·排序算法
xindafu2 小时前
代码随想录算法训练营第四十二天|动态规划part9
算法·动态规划
xindafu2 小时前
代码随想录算法训练营第四十五天|动态规划part12
算法·动态规划