From 434ba4ed39cc52d86b9aa7d2ae16e507d1eddd44 Mon Sep 17 00:00:00 2001 From: mengyuan Date: Mon, 22 Nov 2021 20:04:35 +0800 Subject: [PATCH] =?UTF-8?q?update:=20=E5=B9=B3=E8=A1=A1=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91js=E7=89=88=E6=9C=AC=E6=A0=BC=E5=BC=8F=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0110.平衡二叉树.md | 34 +++++++++++++------------------- 1 file changed, 14 insertions(+), 20 deletions(-) diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index a06bff0e..a8dbb0db 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -606,29 +606,23 @@ func abs(a int)int{ ## JavaScript ```javascript var isBalanced = function(root) { - //还是用递归三部曲 + 后序遍历 左右中 当前左子树右子树高度相差大于1就返回-1 + //还是用递归三部曲 + 后序遍历 左右中 当前左子树右子树高度相差大于1就返回-1 // 1. 确定递归函数参数以及返回值 - const getDepth=function(node){ - // 2. 确定递归函数终止条件 - if(node===null){ - return 0; + const getDepth = function(node) { + // 2. 确定递归函数终止条件 + if(node === null) return 0; + // 3. 确定单层递归逻辑 + let leftDepth = getDepth(node.left); //左子树高度 + let rightDepth = getDepth(node.right); //右子树高度 + if(leftDepth === -1) return -1; + if(rightDepth === -1) return -1; + if(Math.abs(leftDepth - rightDepth) > 1) { + return -1; + } else { + return 1 + Math.max(leftDepth, rightDepth); } - // 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; + return !(getDepth(root) === -1); }; ```