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; + } +} +``` +