Skip to content

Commit 763e794

Browse files
committed
refactor Balanced Binary Tree
1 parent 6e134be commit 763e794

File tree

1 file changed

+10
-11
lines changed

1 file changed

+10
-11
lines changed

go/balanced_binary_tree.go

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,22 +4,21 @@ package main
44
import "math"
55

66
type TreeBalance struct {
7-
IsBalanced bool
8-
Height int
7+
isBalanced bool
8+
height int
99
}
1010

1111
func isBalanced(root *TreeNode) bool {
12-
return checkBalance(root).IsBalanced
12+
return checkBalance(root).isBalanced
1313
}
1414

15-
func checkBalance(root *TreeNode) TreeBalance {
15+
func checkBalance(root *TreeNode) *TreeBalance {
1616
if root == nil {
17-
return TreeBalance{true, 0}
17+
return &TreeBalance{true, 0}
1818
}
19-
20-
l, r := checkBalance(root.Left), checkBalance(root.Right)
21-
b := l.IsBalanced && r.IsBalanced &&
22-
math.Abs(float64(l.Height-r.Height)) <= 1.0
23-
h := max(l.Height, r.Height) + 1
24-
return TreeBalance{b, h}
19+
left, right := checkBalance(root.Left), checkBalance(root.Right)
20+
isBalanced := left.isBalanced && right.isBalanced &&
21+
math.Abs(float64(left.height-right.height)) <= 1.0
22+
height := max(left.height, right.height) + 1
23+
return &TreeBalance{isBalanced, height}
2524
}

0 commit comments

Comments
 (0)