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 c1b11bc

Browse files
committed
feat: update lcof problem: No.68 - I
更新剑指 Offer 题解:面试题68 - I. 二叉搜索树的最近公共祖先
1 parent 44cb5a3 commit c1b11bc

File tree

1 file changed

+23
-1
lines changed
  • lcof/面试题68 - I. 二叉搜索树的最近公共祖先

1 file changed

+23
-1
lines changed

‎lcof/面试题68 - I. 二叉搜索树的最近公共祖先/README.md‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,13 +33,16 @@
3333

3434
## 解法
3535
<!-- 这里可写通用的实现逻辑 -->
36-
从上到下搜索,找到第一个值位于 `[p, q]` 之间的结点即可。
36+
37+
从上到下搜索,找到第一个值位于 `[p, q]` 之间的结点即可。既可以用迭代实现,也可以用递归实现。
3738

3839
<!-- tabs:start -->
3940

4041
### **Python3**
4142
<!-- 这里可写当前语言的特殊实现逻辑 -->
4243

44+
#### 迭代法
45+
4346
```python
4447
# Definition for a binary tree node.
4548
# class TreeNode:
@@ -61,6 +64,25 @@ class Solution:
6164
return root
6265
```
6366

67+
#### 递归法
68+
69+
```python
70+
# Definition for a binary tree node.
71+
# class TreeNode:
72+
# def __init__(self, x):
73+
# self.val = x
74+
# self.left = None
75+
# self.right = None
76+
77+
class Solution:
78+
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
79+
if root.val < p.val and root.val < q.val:
80+
return self.lowestCommonAncestor(root.right, p, q)
81+
if root.val > p.val and root.val > q.val:
82+
return self.lowestCommonAncestor(root.left, p, q)
83+
return root
84+
```
85+
6486
### **Java**
6587
<!-- 这里可写当前语言的特殊实现逻辑 -->
6688

0 commit comments

Comments
(0)

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