From f3b21c7984039eaa37c8da08eac725e6c8d1e11b Mon Sep 17 00:00:00 2001 From: "xeniaxie(xl)" Date: Sat, 26 Jun 2021 21:12:39 +0800 Subject: [PATCH] =?UTF-8?q?0236=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84?= =?UTF-8?q?=E6=9C=80=E8=BF=91=E5=85=AC=E5=85=B1=E7=A5=96=E5=85=88JavaScrip?= =?UTF-8?q?t=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0236.二叉树的最近公共祖先.md | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/problems/0236.二叉树的最近公共祖先.md b/problems/0236.二叉树的最近公共祖先.md index 2f7aa6c3..7673a0ab 100644 --- a/problems/0236.二叉树的最近公共祖先.md +++ b/problems/0236.二叉树的最近公共祖先.md @@ -310,7 +310,31 @@ func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { return nil } ``` - +JavaScript版本: +```javascript +var lowestCommonAncestor = function(root, p, q) { + // 使用递归的方法 + // 需要从下到上,所以使用后序遍历 + // 1. 确定递归的函数 + const travelTree = function(root,p,q) { + // 2. 确定递归终止条件 + if(root === null || root === p||root === q) { + return root; + } + // 3. 确定递归单层逻辑 + let left = travelTree(root.left,p,q); + let right = travelTree(root.right,p,q); + if(left !== null&&right !== null) { + return root; + } + if(left ===null) { + return right; + } + return left; + } + return travelTree(root,p,q); +}; +``` -----------------------