File tree Expand file tree Collapse file tree 1 file changed +23
-1
lines changed
lcof/面试题68 - I. 二叉搜索树的最近公共祖先 Expand file tree Collapse file tree 1 file changed +23
-1
lines changed Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments