diff --git a/problems/0236.二叉树的最近公共祖先.md b/problems/0236.二叉树的最近公共祖先.md index 2f7aa6c3..2413af1d 100644 --- a/problems/0236.二叉树的最近公共祖先.md +++ b/problems/0236.二叉树的最近公共祖先.md @@ -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)