二叉树最近的叶节点
难度:
标签:
题目描述
代码结果
运行时间: 34 ms, 内存: 17.2 MB
/*
* Problem: Find the closest leaf node in a binary tree.
* Approach:
* 1. Use a modified BFS approach utilizing Java Streams.
* 2. Traverse the tree level by level.
* 3. If a leaf node is found, return its value.
*/
import java.util.*;
import java.util.stream.*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class ClosestLeafInBinaryTreeStream {
public int findClosestLeaf(TreeNode root) {
if (root == null) return -1;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
List<TreeNode> level = new ArrayList<>();
while (!queue.isEmpty()) {
level.add(queue.poll());
}
for (TreeNode node : level) {
if (node.left == null && node.right == null) {
return node.val; // Found a leaf node
}
}
queue.addAll(level.stream()
.flatMap(n -> Stream.of(n.left, n.right))
.filter(Objects::nonNull)
.collect(Collectors.toList()));
}
return -1; // In case no leaf node is found
}
}
解释
方法:
这个题解的思路是先通过 DFS 找到值为 k 的节点作为起点,同时在 DFS 过程中为每个节点记录其父节点。然后从起点开始进行 BFS 搜索,第一个遇到的叶子节点即为离起点最近的叶子节点。在 BFS 的过程中需要记录已访问过的节点避免重复访问。
时间复杂度:
O(n)
空间复杂度:
O(n)
代码细节讲解
🦆
为什么在执行DFS时,除了寻找值为k的节点,还需要记录每个节点的父节点?
▷🦆
在BFS阶段,如何保证从起点开始搜索到的第一个叶节点是最近的叶节点?
▷🦆
如果树中存在多个值为k的节点,这个算法如何处理?会找到哪一个?
▷🦆
在BFS中使用队列时,将节点加入队列前进行的`nxt not in vis and nxt`检查是基于什么考虑?
▷