Movatterモバイル変換


[0]ホーム

URL:


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

Commit2f514cd

Browse files
authored
添加0235.二叉搜索树的最近公共祖先 go版本
添加0235.二叉搜索树的最近公共祖先 go版本
1 parent8c1a38b commit2f514cd

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

‎problems/0235.二叉搜索树的最近公共祖先.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,54 @@ class Solution:
265265
else:return root
266266
```
267267
Go:
268+
> BSL法
269+
270+
```go
271+
/**
272+
* Definition for a binary tree node.
273+
* type TreeNode struct {
274+
* Val int
275+
* Left *TreeNode
276+
* Right *TreeNode
277+
* }
278+
*/
279+
//利用BSL的性质(前序遍历有序)
280+
funclowestCommonAncestor(root, p, q*TreeNode)*TreeNode {
281+
if root==nil{return nil}
282+
if root.Val>p.Val&&root.Val>q.Val{//当前节点的值大于给定的值,则说明满足条件的在左边
283+
return lowestCommonAncestor(root.Left,p,q)
284+
}else if root.Val<p.Val&&root.Val<q.Val{//当前节点的值小于各点的值,则说明满足条件的在右边
285+
return lowestCommonAncestor(root.Right,p,q)
286+
}else {return root}//当前节点的值在给定值的中间(或者等于),即为最深的祖先
287+
}
288+
```
289+
290+
> 普通法
291+
292+
```go
293+
/**
294+
* Definition for a binary tree node.
295+
* type TreeNode struct {
296+
* Val int
297+
* Left *TreeNode
298+
* Right *TreeNode
299+
* }
300+
*/
301+
//递归会将值层层返回
302+
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
303+
//终止条件
304+
if root==nil||root.Val==p.Val||root.Val==q.Val{return root}//最后为空或者找到一个值时,就返回这个值
305+
//后序遍历
306+
findLeft:=lowestCommonAncestor(root.Left,p,q)
307+
findRight:=lowestCommonAncestor(root.Right,p,q)
308+
//处理单层逻辑
309+
if findLeft!=nil&&findRight!=nil{return root}//说明在root节点的两边
310+
if findLeft==nil{//左边没找到,就说明在右边找到了
311+
return findRight
312+
}else {return findLeft}
313+
}
314+
```
315+
268316

269317

270318

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp