Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

236. Lowest Common Ancestor of a Binary Tree #152

Open
Tcdian opened this issue May 10, 2020 · 1 comment
Open

236. Lowest Common Ancestor of a Binary Tree #152

Tcdian opened this issue May 10, 2020 · 1 comment
Labels

Comments

@Tcdian
Copy link
Owner

Tcdian commented May 10, 2020

236. Lowest Common Ancestor of a Binary Tree

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

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

例如,给定如下二叉树:  root = [3,5,1,6,2,0,8,null,null,7,4]

Example 1

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.

Example 2

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Note

  • 所有节点的值都是唯一的。
  • p、q 为不同节点且均存在于给定的二叉树中。
@Tcdian
Copy link
Owner Author

Tcdian commented May 10, 2020

Solution

  • JavaScript Solution
/**
 * 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) {
    let pPath;
    let qPath;
    const path = [];
    dfs(root);
    let result;
    for (let i = 0; i < pPath.length; i++) {
        if (pPath[i] !== qPath[i]) {
            break;
        }
        result = pPath[i];
    }
    return result;
    
    function dfs(root) {
        if (pPath && qPath) {
            return;
        }
        path.push(root);
        if (root === p) {
            pPath = [...path];
        }
        if (root === q) {
            qPath = [...path];
        }
        if (root.left) {
            dfs(root.left);
            path.pop();
        }
        if (root.right) {
            dfs(root.right);
            path.pop();
        }
    }
};

@Tcdian Tcdian added the Tree label May 10, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant