Skip to content

Latest commit

 

History

History
37 lines (33 loc) · 1.22 KB

Lowest Common Ancestor of a Binary Tree.md

File metadata and controls

37 lines (33 loc) · 1.22 KB

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).”

Screen Shot 2021-11-27 at 15 51 35

Screen Shot 2021-11-27 at 15 51 43

/**
 * 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);
    let right = lowestCommonAncestor(root.right, p, q);
    if(!left) {
        return right;
    }
    if(!right) {
        return left
    }
    return root
};