系列文章目录
第六章:二叉树习题之第十六题;LeetCode 513. 找树左下角的值
前言
本题为二叉树章节习题之一,LeetCode 513. 找树左下角的值,本文讲解该习题的思想与逻辑,并附有完整可运行的代码。
一、题目简介
给定一个二叉树的 根节点 root
,请找出该二叉树的 最底层 最左边 节点的值。
假设二叉树中至少有一个节点。
示例一
输入: root = [2,1,3]
输出: 1
示例二
输入: [1,2,3,4,null,5,6,null,null,7]
输出: 7
二、思想逻辑
本题的理解并不是很难,但需要我们明确在二叉树的一些相关的知识点及题意的理解。
假定一棵二叉树 1
/ \
2 3
/ \ / \
4 5 5 6
/
7
第一、二叉树的最大深度?
二叉树的最大深度就是深度最大的叶子结点或高度最小的叶子结点。
第二、如何求最靠左侧的叶子结点?
因为本题中没有处理中结点的逻辑,所以可以使用前序遍历(中左右),中序遍历(左中右),或后序遍历(左右中)来求最靠左侧的叶子节点。
第三、最靠左侧结点一定是左孩子吗?
当然不是,在满足最后一行的条件前提下,左右孩子都可以,只需要优先遍历左侧孩子,其次右侧孩子就是可以。
迭代法逻辑:
这道题目使用迭代法显而易见的不是很难,我们只需要使用层序遍历,取到最后一层的第一个节点的值就可以了。
1.解读代码
片段代码如下:递归法
当明确上述的条件后,我们就知道了该题的具体实现逻辑
第一步、确定递归函数的参数和返回值
public void traversal(TreeNode root, int depth){
第二步、确定终止条件
if(root == null) return ;
if(root.left == null && root.right == null){
第三步、处理逻辑
if(depth > maxDepth){
maxDepth = depth;
result = root.val;
片段代码如下:迭代法
if(i == 0){
val = temp.val;
}
这里有一个核心逻辑就是为什么 i 要等同于 0 ?
在这里我们借助上面的假定二叉树,代码中的end代表着二叉树每一层的元素的个数,而i等同于0则代表着每一层遍历的第一个元素,所以满足第一个节点的要求,如果使用调试就会发现,当i等同于0时,val 先后等于
1、2、4、7
。
2.完整代码
代码如下(示例):递归法
class Solution {
//全局变量 记录最大深度
private int maxDepth = Integer.MIN_VALUE;
//全局变量 最大深度最左节点的数值
private int result = 0;
public int findBottomLeftValue(TreeNode root) {
result = root.val;
traversal(root, 0);
return result;
}
public void traversal(TreeNode root, int depth){
//找到叶子结点
if(root.left == null && root.right == null){
if(depth > maxDepth){
maxDepth = depth;// 更新最大深度
result = root.val;// 最大深度最左面的数值
}
}
if(root.left != null){
depth++;//回溯
traversal(root.left, depth);
depth--;
}
if(root.right != null){
depth++;//回溯
traversal(root.right, depth);
depth--;
}
}
}
精简版
class Solution {
private int maxDepth = Integer.MIN_VALUE;
private int result = 0;
public int findBottomLeftValue(TreeNode root) {
result = root.val;
traversal(root, 0);
return result;
}
public void traversal(TreeNode root, int depth){
if(root == null) return ;
if(root.left == null && root.right == null){
if(depth > maxDepth){
maxDepth = depth;
result = root.val;
}
}
if(root.left != null) traversal(root.left, depth + 1);
if(root.right != null) traversal(root.right, depth + 1);
}
}
代码如下(示例):迭代法(层序遍历)
class Solution {
public int findBottomLeftValue(TreeNode root) {
Deque<TreeNode> que = new LinkedList<>();
if(root != null) que.offer(root);
int val = Integer.MIN_VALUE;
while(!que.isEmpty()){
int end = que.size();
for(int i = 0; i < end; i++){
TreeNode temp = que.poll();
if(i == 0){
val = temp.val;
}
if(temp.left != null) que.offer(temp.left);
if(temp.right != null) que.offer(temp.right);
}
}
return val;
}
}
总结
以上就是本文要讲的内容,本文仅仅简单介绍了二叉树的深度,和习题的思路讲解希望本文对你有帮助,再见。