We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 44cb5a3 commit c1b11bcCopy full SHA for c1b11bc
lcof/面试题68 - I. 二叉搜索树的最近公共祖先/README.md
@@ -33,13 +33,16 @@
33
34
## 解法
35
<!-- 这里可写通用的实现逻辑 -->
36
-从上到下搜索,找到第一个值位于 `[p, q]` 之间的结点即可。
+
37
+从上到下搜索,找到第一个值位于 `[p, q]` 之间的结点即可。既可以用迭代实现,也可以用递归实现。
38
39
<!-- tabs:start -->
40
41
### **Python3**
42
<!-- 这里可写当前语言的特殊实现逻辑 -->
43
44
+#### 迭代法
45
46
```python
47
# Definition for a binary tree node.
48
# class TreeNode:
@@ -61,6 +64,25 @@ class Solution:
61
64
return root
62
65
```
63
66
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
86
### **Java**
87
88
AltStyle によって変換されたページ (->オリジナル) / アドレス: モード: デフォルト 音声ブラウザ ルビ付き 配色反転 文字拡大 モバイル
0 commit comments