Algorithm/src/main/java/tree/LowestCommonAncestor.java
2025-03-25 15:57:54 +08:00

48 lines
1.6 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package tree;
import java.util.HashMap;
import java.util.HashSet;
/**
* 题目: 236. 二叉树的最近公共祖先 (lowestCommonAncestor)
* 描述:给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
* 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q最近公共祖先表示为一个节点 x满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
* 链接https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/
*/
public class LowestCommonAncestor {
void helper(HashMap<TreeNode, TreeNode> map, TreeNode father, TreeNode cur) {
if (cur == null)
return;
map.put(cur, father);
helper(map, cur, cur.left);
helper(map, cur, cur.right);
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
HashMap<TreeNode, TreeNode> map = new HashMap<>();
HashSet<TreeNode> set = new HashSet<>();
map.put(root, null);
helper(map, root, root.left);
helper(map, root, root.right);
// 将 p 以及其所有祖先加入 set
TreeNode tp = p;
while (tp != null) {
set.add(tp);
tp = map.get(tp);
}
// 从 q 开始,找到第一个出现在 p 祖先链中的节点
tp = q;
while (tp != null) {
if (set.contains(tp))
return tp;
tp = map.get(tp);
}
return null; // 理论上不可能执行到这里,因为肯定存在公共祖先
}
}