From 1287679e8eedc2c49b5e61946a15445e345b4cf4 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Sun, 4 Dec 2022 23:10:10 +0800 Subject: [PATCH] =?UTF-8?q?update=200235.=E4=BA=8C=E5=8F=89=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E6=A0=91=E7=9A=84=E6=9C=80=E8=BF=91=E5=85=AC=E5=85=B1?= =?UTF-8?q?=E7=A5=96=E5=85=88:=20=E6=9B=BF=E6=8D=A2=20go=20=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...35.二叉搜索树的最近公共祖先.md | 30 ++++++++++++------- 1 file changed, 19 insertions(+), 11 deletions(-) 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