Skip to content

Commit b87fe3a

Browse files
committed
0110.平衡二叉树JavaScript版本
1 parent 648a3ff commit b87fe3a

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

problems/0110.平衡二叉树.md

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ int getDepth(TreeNode* node)
142142
143143
2. 明确终止条件
144144
145-
递归的过程中依然是遇到空节点了为终止,返回0,表示当前节点为根节点的书高度为0
145+
递归的过程中依然是遇到空节点了为终止,返回0,表示当前节点为根节点的树高度为0
146146
147147
代码如下:
148148
@@ -534,7 +534,34 @@ func abs(a int)int{
534534
return a
535535
}
536536
```
537-
537+
JavaScript:
538+
```javascript
539+
var isBalanced = function(root) {
540+
//还是用递归三部曲 + 后序遍历 左右中 当前左子树右子树高度相差大于1就返回-1
541+
// 1. 确定递归函数参数以及返回值
542+
const getDepth=function(node){
543+
// 2. 确定递归函数终止条件
544+
if(node===null){
545+
return 0;
546+
}
547+
// 3. 确定单层递归逻辑
548+
let leftDepth=getDepth(node.left);//左子树高度
549+
if(leftDepth===-1){
550+
return -1;
551+
}
552+
let rightDepth=getDepth(node.right);//右子树高度
553+
if(rightDepth===-1){
554+
return -1;
555+
}
556+
if(Math.abs(leftDepth-rightDepth)>1){
557+
return -1;
558+
}else{
559+
return 1+Math.max(leftDepth,rightDepth);
560+
}
561+
}
562+
return getDepth(root)===-1?false:true;
563+
};
564+
```
538565

539566

540567
-----------------------

0 commit comments

Comments
 (0)