mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
JavaScript版本的《二叉的最近公共祖先》
This commit is contained in:
@ -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)
|
||||
|
Reference in New Issue
Block a user