diff --git a/problems/0235.二叉搜索树的最近公共祖先.md b/problems/0235.二叉搜索树的最近公共祖先.md index c90b3d8c..391d1cfb 100644 --- a/problems/0235.二叉搜索树的最近公共祖先.md +++ b/problems/0235.二叉搜索树的最近公共祖先.md @@ -303,14 +303,22 @@ class Solution: 递归法: ```go -//利用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 { + root = root.Left + } + if root.Val < p.Val && root.Val < q.Val { + root = root.Right + } + if (root.Val - p.Val) * (root.Val - q.Val) <= 0 { + return root + } + } + return root } ``` @@ -326,11 +334,11 @@ var lowestCommonAncestor = function(root, p, q) { if(root === null) { return root; } - if(root.val>p.val&&root.val>q.val) { + if(root.val > p.val && root.val > q.val) { // 向左子树查询 return root.left = lowestCommonAncestor(root.left,p,q); } - if(root.valp.val&&root.val>q.val) { + if(root.val > p.val && root.val > q.val) { root = root.left; - }else if(root.val