diff --git a/problems/0235.二叉搜索树的最近公共祖先.md b/problems/0235.二叉搜索树的最近公共祖先.md index 15ff7af4..d78db42a 100644 --- a/problems/0235.二叉搜索树的最近公共祖先.md +++ b/problems/0235.二叉搜索树的最近公共祖先.md @@ -265,6 +265,54 @@ class Solution: else: return root ``` 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 普通法 + +```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} +} +``` +