June 30, 2021 Andrey

Lowest Common Ancestor in a Binary Tree LeetCode problem in JS solved with comparing vector path to each node

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Solution

Recursive function to find a path to a node and storing vector path in the array

After finding both paths compare them and return the latest element before arrays diverge.

/**
 * 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) {
    var pathOne = [];
    var pathTwo = [];
    
    findPath(root, pathOne, p.val);
    findPath(root, pathTwo, q.val);

    var i = 0;
    for (i = 0; i < pathOne.length && i < pathTwo.length ; i++) {
        if (pathOne[i].val != pathTwo[i].val)
            break;
    }

    return pathOne[i-1];
};

var findPath = function(root, path, nodeToFind) {
     // base case
    if (root == null) return false;
 
    // Store this node in path vector. The node will be removed if
    // not in path from root to k
    path.push(root);
 
    // See if the nodeToFind is same as root's key
    if (root.val == nodeToFind)
        return true;
 
    // Check if nodeToFind is found in left or right sub-tree
    if ( (root.left && findPath(root.left, path, nodeToFind)) ||
         (root.right && findPath(root.right, path, nodeToFind)) )
        return true;
 
    // If not present in subtree rooted with root, remove root from
    // path[] and return false
    path.pop();
    return false;
}