add: 二叉树的最近公共祖先

This commit is contained in:
2020-05-10 15:30:48 +08:00
parent 1227f993ae
commit 64941ec538
3 changed files with 33 additions and 0 deletions

View File

@ -0,0 +1,20 @@
/**
* 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
}