add: 二叉树的最近公共祖先
This commit is contained in:
20
src/tree/lowest-common-ancestor-of-a-binary-tree.js
Normal file
20
src/tree/lowest-common-ancestor-of-a-binary-tree.js
Normal 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
|
||||
}
|
Reference in New Issue
Block a user