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