Skip to content

Commit b96a774

Browse files
author
Shuo
authored
Merge pull request #741 from openset/develop
Add: Balanced Binary Tree
2 parents 6d44c84 + 0bccb04 commit b96a774

File tree

2 files changed

+47
-18
lines changed

2 files changed

+47
-18
lines changed

problems/balanced-binary-tree/balanced_binary_tree.go

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -14,26 +14,25 @@ type TreeNode = kit.TreeNode
1414
* }
1515
*/
1616
func isBalanced(root *TreeNode) bool {
17-
_, isBalanced := recur(root)
18-
return isBalanced
19-
}
20-
21-
func recur(root *TreeNode) (int, bool) {
22-
if root == nil {
23-
return 0, true
24-
}
25-
leftDepth, leftIsBalanced := recur(root.Left)
26-
rightDepth, rightIsBalanced := recur(root.Right)
27-
if leftIsBalanced && rightIsBalanced &&
28-
-1 <= leftDepth-rightDepth && leftDepth-rightDepth <= 1 {
29-
return max(leftDepth, rightDepth) + 1, true
17+
if root != nil {
18+
left := depth(root.Left)
19+
right := depth(root.Right)
20+
if left > right+1 || left < right-1 {
21+
return false
22+
}
23+
return isBalanced(root.Left) && isBalanced(root.Right)
3024
}
31-
return 0, false
25+
return true
3226
}
3327

34-
func max(a, b int) int {
35-
if a > b {
36-
return a
28+
func depth(root *TreeNode) int {
29+
if root != nil {
30+
left := depth(root.Left) + 1
31+
right := depth(root.Right) + 1
32+
if left > right {
33+
return left
34+
}
35+
return right
3736
}
38-
return b
37+
return 0
3938
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,31 @@
11
package problem110
2+
3+
import (
4+
"testing"
5+
6+
"github.com/openset/leetcode/internal/kit"
7+
)
8+
9+
type testType struct {
10+
in []int
11+
want bool
12+
}
13+
14+
func TestIsBalanced(t *testing.T) {
15+
tests := [...]testType{
16+
{
17+
in: []int{3, 9, 20, kit.NULL, kit.NULL, 15, 7},
18+
want: true,
19+
},
20+
{
21+
in: []int{1, 2, 2, 3, 3, kit.NULL, kit.NULL, 4, 4},
22+
want: false,
23+
},
24+
}
25+
for _, tt := range tests {
26+
got := isBalanced(kit.SliceInt2TreeNode(tt.in))
27+
if got != tt.want {
28+
t.Fatalf("in: %v, got: %v, want: %v", tt.in, got, tt.want)
29+
}
30+
}
31+
}

0 commit comments

Comments
 (0)