Skip to content

Commit 3f932cf

Browse files
aQuaaQua
aQua
authored and
aQua
committed
110 finish. 19ms.
1 parent a65a7e3 commit 3f932cf

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

Algorithms/0110.balanced-binary-tree/balanced-binary-tree.go

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,29 @@ import (
77
type TreeNode = kit.TreeNode
88

99
func isBalanced(root *TreeNode) bool {
10+
_, isBalanced := cur(root)
11+
return isBalanced
12+
}
13+
14+
func cur(root *TreeNode) (int, bool) {
15+
if root == nil {
16+
return 0, true
17+
}
18+
19+
leftDeepth, leftIsBalanced := cur(root.Left)
20+
rightDeepth, rightIsBalanced := cur(root.Right)
21+
22+
if leftIsBalanced && rightIsBalanced &&
23+
-1 <= leftDeepth-rightDeepth && leftDeepth - rightDeepth <= 1 {
24+
return max(leftDeepth, rightDeepth) + 1, true
25+
}
26+
27+
return 0, false
28+
}
1029

11-
return true
30+
func max(a, b int) int {
31+
if a > b {
32+
return a
33+
}
34+
return b
1235
}

0 commit comments

Comments
 (0)