|
|
|
@ -596,3 +596,45 @@ class Solution { |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
``` |
|
|
|
|
|
|
|
|
|
#### [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; |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
``` |
|
|
|
|
|
|
|
|
|