JavaScript版本的《二叉的最近公共祖先》

This commit is contained in:
kok-s0s
2021-06-21 21:35:19 +08:00
parent 4f66b8679c
commit b33da0c412

View File

@ -311,7 +311,34 @@ func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
}
```
JavaScript版本
```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}
*/
var lowestCommonAncestor = function(root, p, q) {
if(root === p || root === q || root === null)
return root;
let left = lowestCommonAncestor(root.left, p , q);
let right = lowestCommonAncestor(root.right, p, q);
if(left && right)
return root;
if(!left)
return right;
return left;
};
```
-----------------------
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)