Skip to content

📚 22.二叉搜索树的最近公共祖先

💻 代码实现

typescript
/**
 * @url https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/
 */

class TreeNode {
    val: number
    left: TreeNode | null
    right: TreeNode | null
    constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
        this.val = val === undefined ? 0 : val
        this.left = left === undefined ? null : left
        this.right = right === undefined ? null : right
    }
}
function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null {
    if (!root) return null
    if (root === q || root === p) return root

    if (root.val > p!.val && root.val > q!.val) {
        const left = lowestCommonAncestor(root.left, p, q)
        if (left) {
            return left
        }
    }
    if (root.val < p!.val && root.val < q!.val) {
        const right = lowestCommonAncestor(root.right, p, q)
        if (right) {
            return right
        }
    }
    const left = lowestCommonAncestor(root.left, p, q)
    const right = lowestCommonAncestor(root.right, p, q)
    if (!left && right) return right
    if (left && !right) return left
    if (left && right) return root
    return null
}

Released under the MIT License.