Typescript-Algorithms
    Preparing search index...

    Variable lowest_common_ancestor_of_a_binary_treeConst

    lowest_common_ancestor_of_a_binary_tree: (
        root: null | TreeNode,
        p: null | TreeNode,
        q: null | TreeNode,
    ) => null | TreeNode = lowestCommonAncestor

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

    给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

    最近公共祖先的定义为:"对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。"


    示例1

    输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1

    输出: 3 解释: 节点 5 和节点 1 的最近公共祖先是节点 3 。


    示例2

    输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4

    输出: 5 解释: 节点 5 和节点 4 的最近公共祖先是节点 5 。因为根据定义最近公共祖先节点可以为节点本身。


    • 树中节点数目在范围 [2, 10^5] 内。
    • -10^9 <= Node.val <= 10^9
    • 所有 Node.val 互不相同 。
    • p != q
    • pq 均存在于给定的二叉树中。

    Type declaration

      • (root: null | TreeNode, p: null | TreeNode, q: null | TreeNode): null | TreeNode
      • Definition for a binary tree node. 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) } }

        Parameters

        • root: null | TreeNode
        • p: null | TreeNode
        • q: null | TreeNode

        Returns null | TreeNode

    核心思路: 利用递归方法,在二叉树中寻找节点p和q的最近公共祖先。

    递归终止条件

    • 当前节点为null
    • 当前节点等于p或q

    递归逻辑分析

    情况1:p、q分别在左右子树中

         root
    / \
    p q
    • 左子树返回p,右子树返回q
    • 此时root就是最近公共祖先

    情况2:p、q都在同一侧子树中

         root
    /
    p
    /
    q
    • 假设p、q都在左子树中
    • 左子树返回p(或q),右子树返回null
    • 此时p就是最近公共祖先

    算法步骤

    1. 递归遍历左右子树
    2. 如果左右子树都返回非空值,说明p、q分别在两侧,当前节点是LCA
    3. 如果只有一个子树返回非空值,说明p、q都在该子树中,返回该值
    4. 如果两个子树都返回空,说明当前子树中没有p、q

    时间复杂度:O(n),其中n是树中节点数 空间复杂度:O(h),其中h是树的高度

    /**
    * Definition for a binary tree node.
    * 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 {

    function dfs(node: TreeNode | null): TreeNode | null {
    if (!node || node === p || node === q) {
    return node;
    }

    const l = dfs(node.left);
    const r = dfs(node.right);

    return l && r ? node : (l ?? r);
    }

    return dfs(root)
    };