File tree Expand file tree Collapse file tree 1 file changed +29
-2
lines changed Expand file tree Collapse file tree 1 file changed +29
-2
lines changed Original file line number Diff line number Diff line change @@ -142,7 +142,7 @@ int getDepth(TreeNode* node)
142
142
143
143
2. 明确终止条件
144
144
145
- 递归的过程中依然是遇到空节点了为终止,返回0,表示当前节点为根节点的书高度为0
145
+ 递归的过程中依然是遇到空节点了为终止,返回0,表示当前节点为根节点的树高度为0
146
146
147
147
代码如下:
148
148
@@ -534,7 +534,34 @@ func abs(a int)int{
534
534
return a
535
535
}
536
536
```
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
+ ```
538
565
539
566
540
567
-----------------------
You can’t perform that action at this time.
0 commit comments