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 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 map = new HashMap<>(); HashSet 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; // 理论上不可能执行到这里,因为肯定存在公共祖先 } }