236. 二叉树的最近公共祖先

题目链接

function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null {
    if (root === null) return null;
    if (root === p || root === q) return root;
    const left = lowestCommonAncestor(root.left, p, q);
    const right = lowestCommonAncestor(root.right, p, q);
    if (!left && !right) return null;
    if (left && right) return root;
    if (left) return left;
    if (right) return right;
};

results matching ""

    No results matching ""