Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 15bfcc4

Browse files
🐱(tree): 235. 二叉搜索树的最近公共祖先
1 parent 6bce0ec commit 15bfcc4

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

‎docs/data-structure/tree/recursion/README.md‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -548,6 +548,55 @@ class Solution(object):
548548
return root
549549
```
550550

551+
## 235. 二叉搜索树的最近公共祖先
552+
553+
[原题链接](https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)
554+
555+
### 解一:递归
556+
557+
分为几种情况:
558+
559+
1. `p``q` 分列 `root` 节点两个子树,则直接返回 `root`
560+
2. `p``q` 其中之一等于 `root`,则直接返回 `root`
561+
3. 如果 `p``q` 都在 `root` 左子树,则递归左子树
562+
4. 如果 `p``q` 都在 `root` 右子树,则递归右子树
563+
564+
<!-- tabs:start -->
565+
566+
#### **Python**
567+
568+
```python
569+
# Definition for a binary tree node.
570+
# class TreeNode:
571+
# def __init__(self, x):
572+
# self.val = x
573+
# self.left = None
574+
# self.right = None
575+
576+
class Solution:
577+
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
578+
if root is None:
579+
return root
580+
# 当前节点为 p 或 q
581+
if p.val == root.val or q.val == root.val:
582+
return root
583+
# 两个节点分别在左右两个子树
584+
if (p.val < root.val and q.val > root.val) or (p.val > root.val and q.val < root.val):
585+
return root
586+
# 两个节点都在左子树
587+
if p.val < root.val and q.val < root.val:
588+
return self.lowestCommonAncestor(root.left, p, q)
589+
# 两个节点都在右子树
590+
if p.val > root.val and q.val > root.val:
591+
return self.lowestCommonAncestor(root.right, p, q)
592+
```
593+
594+
<!-- tabs:end -->
595+
596+
### 解二:迭代
597+
598+
@TODO
599+
551600
## 236. 二叉树的最近公共祖先
552601

553602
[原题链接](https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/)(同 [面试题68 - II. 二叉树的最近公共祖先](https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/))

‎docs/offer/README.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -354,4 +354,8 @@ func (this *MaxQueue) Pop_front() int {
354354
*/
355355
```
356356

357-
<!-- tabs:end -->
357+
<!-- tabs:end -->
358+
359+
## 面试题68 - I. 二叉搜索树的最近公共祖先
360+
361+
同:235. 二叉搜索树的最近公共祖先

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /