Skip to content

Commit 0b60def

Browse files
authored
update 0110.平衡二叉树: 替换 go 代码
1 parent ae13f95 commit 0b60def

File tree

1 file changed

+17
-22
lines changed

1 file changed

+17
-22
lines changed

problems/0110.平衡二叉树.md

Lines changed: 17 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ if (node == NULL) {
158158

159159
如何判断以当前传入节点为根节点的二叉树是否是平衡二叉树呢?当然是其左子树高度和其右子树高度的差值。
160160

161-
分别求出其左右子树的高度,然后如果差值小于等于1,则返回当前二叉树的高度,否则则返回-1,表示已经不是二叉平衡树了。
161+
分别求出其左右子树的高度,然后如果差值小于等于1,则返回当前二叉树的高度,否则返回-1,表示已经不是二叉平衡树了。
162162

163163
代码如下:
164164

@@ -342,7 +342,7 @@ public:
342342
343343
**例如:都知道回溯法其实就是递归,但是很少人用迭代的方式去实现回溯算法!**
344344
345-
因为对于回溯算法已经是非常复杂的递归了,如果在用迭代的话,就是自己给自己找麻烦,效率也并不一定高。
345+
因为对于回溯算法已经是非常复杂的递归了,如果再用迭代的话,就是自己给自己找麻烦,效率也并不一定高。
346346
347347
## 总结
348348
@@ -559,37 +559,32 @@ class Solution:
559559
### Go
560560
```Go
561561
func isBalanced(root *TreeNode) bool {
562-
if root==nil{
563-
return true
564-
}
565-
if !isBalanced(root.Left) || !isBalanced(root.Right){
566-
return false
567-
}
568-
LeftH:=maxdepth(root.Left)+1
569-
RightH:=maxdepth(root.Right)+1
570-
if abs(LeftH-RightH)>1{
562+
h := getHeight(root)
563+
if h == -1 {
571564
return false
572565
}
573566
return true
574567
}
575-
func maxdepth(root *TreeNode)int{
576-
if root==nil{
568+
// 返回以该节点为根节点的二叉树的高度,如果不是平衡二叉树了则返回-1
569+
func getHeight(root *TreeNode) int {
570+
if root == nil {
577571
return 0
578572
}
579-
return max(maxdepth(root.Left),maxdepth(root.Right))+1
573+
l, r := getHeight(root.Left), getHeight(root.Right)
574+
if l == -1 || r == -1 {
575+
return -1
576+
}
577+
if l - r > 1 || r - l > 1 {
578+
return -1
579+
}
580+
return max(l, r) + 1
580581
}
581-
func max(a,b int)int{
582-
if a>b{
582+
func max(a, b int) int {
583+
if a > b {
583584
return a
584585
}
585586
return b
586587
}
587-
func abs(a int)int{
588-
if a<0{
589-
return -a
590-
}
591-
return a
592-
}
593588
```
594589

595590
### JavaScript

0 commit comments

Comments
 (0)