Skip to main content

236.js

/** ------------------------------------------------------------------------------
*
* 236. Lowest Common Ancestor of a Binary Tree
* Topics: Tree, Depth-First Search, Binary Tree
* https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/
*
------------------------------------------------------------------------------ */
/**
* 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) return null
if (root === p || root === q) return root

const left = lowestCommonAncestor(root.left, p, q)
const right = lowestCommonAncestor(root.right, p, q)

if (left && right) return root
return left || right
}

console.log(lowestCommonAncestor([3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], 5, 1))