mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
添加0235.二叉搜索树的最近公共祖先 go版本
添加0235.二叉搜索树的最近公共祖先 go版本
This commit is contained in:
@ -265,6 +265,54 @@ class Solution:
|
|||||||
else: return root
|
else: return root
|
||||||
```
|
```
|
||||||
Go:
|
Go:
|
||||||
|
> BSL法
|
||||||
|
|
||||||
|
```go
|
||||||
|
/**
|
||||||
|
* Definition for a binary tree node.
|
||||||
|
* type TreeNode struct {
|
||||||
|
* Val int
|
||||||
|
* Left *TreeNode
|
||||||
|
* Right *TreeNode
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
//利用BSL的性质(前序遍历有序)
|
||||||
|
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
|
||||||
|
if root==nil{return nil}
|
||||||
|
if root.Val>p.Val&&root.Val>q.Val{//当前节点的值大于给定的值,则说明满足条件的在左边
|
||||||
|
return lowestCommonAncestor(root.Left,p,q)
|
||||||
|
}else if root.Val<p.Val&&root.Val<q.Val{//当前节点的值小于各点的值,则说明满足条件的在右边
|
||||||
|
return lowestCommonAncestor(root.Right,p,q)
|
||||||
|
}else {return root}//当前节点的值在给定值的中间(或者等于),即为最深的祖先
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
> 普通法
|
||||||
|
|
||||||
|
```go
|
||||||
|
/**
|
||||||
|
* Definition for a binary tree node.
|
||||||
|
* type TreeNode struct {
|
||||||
|
* Val int
|
||||||
|
* Left *TreeNode
|
||||||
|
* Right *TreeNode
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
//递归会将值层层返回
|
||||||
|
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
|
||||||
|
//终止条件
|
||||||
|
if root==nil||root.Val==p.Val||root.Val==q.Val{return root}//最后为空或者找到一个值时,就返回这个值
|
||||||
|
//后序遍历
|
||||||
|
findLeft:=lowestCommonAncestor(root.Left,p,q)
|
||||||
|
findRight:=lowestCommonAncestor(root.Right,p,q)
|
||||||
|
//处理单层逻辑
|
||||||
|
if findLeft!=nil&&findRight!=nil{return root}//说明在root节点的两边
|
||||||
|
if findLeft==nil{//左边没找到,就说明在右边找到了
|
||||||
|
return findRight
|
||||||
|
}else {return findLeft}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user