Skip to content

二叉树的最近公共祖先 #1072

@pwstrick

Description

@pwstrick

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

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {TreeNode}
 */
var lowestCommonAncestor = function(root, p, q) {
    if(!root || root == p || root == q)
        return root;
    let left = lowestCommonAncestor(root.left, p, q);           //在左子树中查找p和q
    let right = lowestCommonAncestor(root.right, p, q);         //在右子树中查找p和q
    /**
     * left为null,说明p和q在右子树(right)中
     * right为null,说明p和q在左子树(left)中
     * left和right都不为null,说明p和q分别存在于root的左右子树中
     */
    return left == null ? right : (right == null ? left : root);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    LeetcodeLeetcode的题目

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions