From b87fe3a4b3252ac7b6e2e08ff6e4224a073abce1 Mon Sep 17 00:00:00 2001 From: xll <18574553598@163.com> Date: Wed, 26 May 2021 10:36:11 +0800 Subject: [PATCH] =?UTF-8?q?0110.=E5=B9=B3=E8=A1=A1=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91JavaScript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0110.平衡二叉树.md | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index dfc27344..1cd54849 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -142,7 +142,7 @@ int getDepth(TreeNode* node) 2. 明确终止条件 -递归的过程中依然是遇到空节点了为终止,返回0,表示当前节点为根节点的书高度为0 +递归的过程中依然是遇到空节点了为终止,返回0,表示当前节点为根节点的树高度为0 代码如下: @@ -534,7 +534,34 @@ func abs(a int)int{ return a } ``` - +JavaScript: +```javascript +var isBalanced = function(root) { + //还是用递归三部曲 + 后序遍历 左右中 当前左子树右子树高度相差大于1就返回-1 + // 1. 确定递归函数参数以及返回值 + const getDepth=function(node){ + // 2. 确定递归函数终止条件 + if(node===null){ + return 0; + } + // 3. 确定单层递归逻辑 + let leftDepth=getDepth(node.left);//左子树高度 + if(leftDepth===-1){ + return -1; + } + let rightDepth=getDepth(node.right);//右子树高度 + if(rightDepth===-1){ + return -1; + } + if(Math.abs(leftDepth-rightDepth)>1){ + return -1; + }else{ + return 1+Math.max(leftDepth,rightDepth); + } + } + return getDepth(root)===-1?false:true; +}; +``` -----------------------