js-practice/src/tree/lowest-common-ancestor-of-a-binary-tree.js

21 lines
566 B
JavaScript

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