代码随想录——找树左下角的值(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;
    }
}
相关推荐
1点东西3 分钟前
新来的同事问我当进程/机器突然停止时,finally 到底会不会执行?
java·后端·程序员
呼啸长风8 分钟前
漫谈散列函数
算法
NAGNIP12 分钟前
彻底搞懂 RoPE:位置编码的新范式
算法
NAGNIP19 分钟前
一文搞懂位置编码Positional Encoding
算法
Aspartame~33 分钟前
K8s的相关知识总结
java·容器·kubernetes
寒士obj1 小时前
MyBatis-Plus基础篇详解
java·mybatis
我崽不熬夜1 小时前
List、Set、Map,你真的会选用吗?
java·后端·java ee
Ghost-Face1 小时前
关于模运算
算法
SunnyKriSmile1 小时前
指针实现数组的逆序存放并输出
c语言·算法·排序算法·数组逆序存放
Y4090011 小时前
Java算法之排序
java·数据结构·笔记·算法