513.找树左下角的值
一、题目描述
给定一个二叉树,在树的最后一行找到最左边的值。
示例1:
示例2:
提示:
- 二叉树的节点个数的范围是 [1,10^4]
- -231 <= Node.val <= 231 - 1
二、解题思路
找到最底层最左边的值。
1.递归法
使用递归法有两个问题
- 如何判断是最后一行呢,其实就是深度最大的叶子节点一定是最后一行。
- 如何判断是最左边的呢,可以使用前序遍历,这样才先优先左边搜索,然后记录深度最大的叶子节点,此时就是树的最后一行最左边的值。(其实前、中、后都可)
综上,可用一个变量A记录最大深度,一个变量B记录最大深度最左节点的值。每次遍历到更大深度时就顺便修改B,遍历结束时B即是所求。
2.迭代法(层序遍历)
对二叉数进行层序遍历,遍历到最底层的第一个数就是左下角的值。
三、AC代码
1.递归法
class Solution {
int maxDeep = -1;
int value = 0;
public int findBottomLeftValue(TreeNode root) {
value = root.val;
findLeftValue(root, 0);
return value;
}
void findLeftValue(TreeNode root, int deep) {
if (root == null) {
return ;
}
findLeftValue(root.left, deep+1);
findLeftValue(root.right, deep+1);
if (deep > maxDeep) {
maxDeep = deep;
value = root.val;
}
}
}
2.迭代法(层序遍历)
class Solution {
public int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int result = 0;
while (!queue.isEmpty()) {
int length = queue.size();
for (int i = 0; i < length; i++) {
TreeNode node = queue.poll();
if (i == 0) {
result = node.val;
}
if (null != node.left) {
queue.offer(node.left);
}
if (null != node.right) {
queue.offer(node.right);
}
}
}
return result;
}
}
参考代码随想录:https://programmercarl.com/