diff --git a/8 Algorithms Analysis/递归.md b/8 Algorithms Analysis/递归.md index 7f6b53f..0374c7f 100644 --- a/8 Algorithms Analysis/递归.md +++ b/8 Algorithms Analysis/递归.md @@ -233,6 +233,24 @@ public static LinkedNode mergeSeqLink(LinkedNode l1, LinkedNode l2){ ```Java +TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + // base case + if (root == null) return null; + if (root == p || root == q) return root; + + TreeNode left = lowestCommonAncestor(root.left, p, q); + TreeNode right = lowestCommonAncestor(root.right, p, q); + // 情况 1 + if (left != null && right != null) { + return root; + } + // 情况 2 + if (left == null && right == null) { + return null; + } + // 情况 3 + return left == null ? right : left; +} ```