1、题目描述
给定一个二叉树的 根节点 root
,请找出该二叉树的 最底层 最左边 节点的值。
假设二叉树中至少有一个节点。
2、算法分析
这题可以使用BFS,也就是层次遍历。
思路如下:
使用队列对二叉树进行层次遍历,注意最关键的是找到最后一层,当count(层次遍历的深度)等于二叉树的最大深度的时候,队列中出队的第一个元素就是最底层,最左边的元素值。
看代码注释详细:
3、代码实现
/**
* 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) {
if(root.left == null && root.right == null){
return root.val;
}
// 入队root
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
// 定义深度为1,层次遍历一层,深度加一层。
int count = 1;
// 找到二叉树的最大深度
int max = maxHeight(root);
// 定义结果结点值
TreeNode leftVal = null;
// 遍历队列
while(!queue.isEmpty()){
// 队列大小
int size = queue.size();
// 每一层深度+1
++count;
// 遍历这一层,下一层的元素入队
for(int i = 0;i < size;i++){
// 注意这儿是出队的。
TreeNode node = queue.poll();
if(node.left != null){
queue.offer(node.left);
}
if(node.right != null){
queue.offer(node.right);
}
}
// 每一层遍历,判断深度是否为二叉树的高度最大值
if(count == max){
leftVal = queue.poll();
}
}
// 返回。
return leftVal.val;
}
public int maxHeight(TreeNode root){
if(root == null){
return 0;
}
return Math.max(maxHeight(root.left),maxHeight(root.right)) + 1;
}
}