From b33da0c412e49d67610bc7d6016c8e51541da637 Mon Sep 17 00:00:00 2001 From: kok-s0s <2694308562@qq.com> Date: Mon, 21 Jun 2021 21:35:19 +0800 Subject: [PATCH] =?UTF-8?q?JavaScript=E7=89=88=E6=9C=AC=E7=9A=84=E3=80=8A?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E7=9A=84=E6=9C=80=E8=BF=91=E5=85=AC=E5=85=B1?= =?UTF-8?q?=E7=A5=96=E5=85=88=E3=80=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0236.二叉树的最近公共祖先.md | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) 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)