From 4a31531cf6ff7f938f785ce010b5a449edc91227 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A7=BB=E5=8A=A8=E5=BC=80=E5=8F=91=E5=B0=8F=E5=86=89?= <510495266@qq.com> Date: Mon, 15 Nov 2021 01:22:38 +0800 Subject: [PATCH] =?UTF-8?q?Update=20=E9=80=92=E5=BD=92.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 8 Algorithms Analysis/递归.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) 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; +} ```