LeetCode 链接:https://leetcode-cn.com/problems/find-bottom-left-tree-value/
题目:给定一个二叉树,在树的最后一行找到最左边的值。

分析:层次遍历二叉树,并在遍历时记录下一层的个数和当前的层的个数,当当前层的数量为 0 时,如果下一层的节点数量大于0,则更新 val 的值为队列中队首的值。遍历结束时,返回的 val 即为树的最左下角节点的值。
public class FindBottomLeftValue {
public static class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int val){
this.val = val;
}
}
public static int findBottomLeftValue(TreeNode root){
if(root == null){
return Integer.MIN_VALUE;
}
int val = root.val;
int currentNum = 1; // 当前层还剩的节点数
int nextNum = 0; // 下一层的节点数
LinkedList<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
TreeNode node = queue.poll();
if(node.left != null){
queue.add(node.left);
nextNum++; // 下一层节点数加1
}
if(node.right != null){
queue.add(node.right);
nextNum++; // 下一层节点数加1
}
currentNum--; // 当前层节点数减1
// 当当前层节点已经遍历完成,即currentNum=0,并且nextNum不为0的时候,更新val
if(currentNum == 0){
if(nextNum != 0){
val = queue.peek().val;
}
// 否则,继续往下遍历
currentNum = nextNum;
nextNum = 0;
}
}
return val;
}
}

本文介绍了LeetCode第513题的解决方案,通过层次遍历二叉树,寻找最后一行最左边的值。在遍历过程中,利用队列记录每层节点,当进入新层时,若节点数不为0,则更新目标值为该层的第一个节点值。最终返回的目标值即为树的左下角节点值。
171

被折叠的 条评论
为什么被折叠?



