add: 二叉树的最近公共祖先
This commit is contained in:
1 parent
1227f993ae
commit
64941ec538
3 files changed
+33
No files matched your search
@@ -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