找树左下角的值
难度:
标签:
题目描述
English description is not available for the problem. Please switch to Chinese.
代码结果
运行时间: 27 ms, 内存: 17.9 MB
/*
题目思路:
1. 使用深度优先搜索(DFS)来遍历二叉树。
2. 记录每一层最左边节点的值。
3. 使用Java Streams来简化代码。
*/
// Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
import java.util.*;
import java.util.stream.*;
public class Solution {
public int findBottomLeftValue(TreeNode root) {
Map<Integer, Integer> leftmostValues = new HashMap<>();
findBottomLeftValue(root, 0, leftmostValues);
return leftmostValues.entrySet().stream()
.max(Map.Entry.comparingByKey())
.get()
.getValue();
}
private void findBottomLeftValue(TreeNode node, int depth, Map<Integer, Integer> leftmostValues) {
if (node == null) return;
leftmostValues.putIfAbsent(depth, node.val);
findBottomLeftValue(node.left, depth + 1, leftmostValues);
findBottomLeftValue(node.right, depth + 1, leftmostValues);
}
}
解释
方法:
此题解采用深度优先搜索(DFS)来寻找二叉树最底层最左边的节点值。使用两个非局部变量:left来记录当前找到的最左值,curH来记录当前的最大深度。DFS从根节点开始,对每个节点检查其深度是否超过了当前已知的最大深度curH。如果是,更新curH和left。DFS首先访问左子节点,确保最左的节点会被优先记录。
时间复杂度:
O(n)
空间复杂度:
O(n)
代码细节讲解
🦆
为什么在DFS遍历中,先访问左子节点再访问右子节点对于解题特别重要?
▷🦆
在DFS递归函数中,如果当前节点的高度与已知的最大深度相同,为什么不更新最左值?
▷🦆
解题中提到的非局部变量left和curH在递归中是如何更新并保持其最新值的?
▷