From fb1219f5073bfdc0bd0b9e8eae0db5eb18c472db Mon Sep 17 00:00:00 2001 From: Omooo <869759698@qq.com> Date: Wed, 22 Jul 2020 11:01:38 +0800 Subject: [PATCH] =?UTF-8?q?Update=20=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9B=B8?= =?UTF-8?q?=E5=85=B3.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- blogs/Algorithm/剑指 Offer/二叉树相关.md | 44 +++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/blogs/Algorithm/剑指 Offer/二叉树相关.md b/blogs/Algorithm/剑指 Offer/二叉树相关.md index 5dc4cf2..84ff829 100644 --- a/blogs/Algorithm/剑指 Offer/二叉树相关.md +++ b/blogs/Algorithm/剑指 Offer/二叉树相关.md @@ -595,4 +595,46 @@ class Solution { helper(root.left, k); } } -``` \ No newline at end of file +``` + +#### [68 - I. 二叉搜索树的最近公共祖先](https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-zui-jin-gong-gong-zu-xian-lcof/) + +```java +class Solution { + + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if (root == null) { + return null; + } + while (root != null) { + if (p.val < root.val && q.val < root.val) { + root = root.left; + } else if (p.val > root.val && q.val > root.val) { + root = root.right; + } else { + break; + } + } + return root; + } +} +``` + +```java +class Solution { + + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if (root == null) { + return null; + } + if (p.val < root.val && q.val < root.val) { + return lowestCommonAncestor(root.left, p, q); + } + if (p.val > root.val && q.val > root.val) { + return lowestCommonAncestor(root.right, p, q); + } + return root; + } +} +``` +