From 95e8b279aef0dab41fce7210ad4f80fd74f8dca8 Mon Sep 17 00:00:00 2001 From: markwang Date: Mon, 25 Dec 2023 15:36:54 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E8=BF=91=E5=85=AC=E5=85=B1=E7=A5=96=E5=85=88?= =?UTF-8?q?Go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...35.二叉搜索树的最近公共祖先.md | 39 +++++++++++-------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/problems/0235.二叉搜索树的最近公共祖先.md b/problems/0235.二叉搜索树的最近公共祖先.md index b27a231e..08d25080 100644 --- a/problems/0235.二叉搜索树的最近公共祖先.md +++ b/problems/0235.二叉搜索树的最近公共祖先.md @@ -48,7 +48,7 @@ 在有序树里,如果判断一个节点的左子树里有p,右子树里有q呢? -因为是有序树,所有 如果 中间节点是 q 和 p 的公共祖先,那么 中节点的数组 一定是在 [p, q]区间的。即 中节点 > p && 中节点 < q 或者 中节点 > q && 中节点 < p。 +因为是有序树,所以 如果 中间节点是 q 和 p 的公共祖先,那么 中节点的数组 一定是在 [p, q]区间的。即 中节点 > p && 中节点 < q 或者 中节点 > q && 中节点 < p。 那么只要从上到下去遍历,遇到 cur节点是数值在[p, q]区间中则一定可以说明该节点cur就是p 和 q的公共祖先。 那问题来了,**一定是最近公共祖先吗**? @@ -328,27 +328,34 @@ class Solution: ``` ### Go -递归法: +递归法 ```go func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { - if root == nil { - return nil - } - for { - 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 - } - } + 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 +func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { + for root != nil { + if root.Val > p.Val && root.Val > q.Val { + root = root.Left + } else if root.Val < p.Val && root.Val < q.Val { + root = root.Right + } else { + return root + } + } + return nil +} +``` ### JavaScript