Skip to content

Commit

Permalink
Merge a527f60 into 06b6b89
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Apr 26, 2019
2 parents 06b6b89 + a527f60 commit c774c66
Show file tree
Hide file tree
Showing 3 changed files with 122 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -258,3 +258,4 @@ problems from
* [Day 244](https://github.com/vaskoz/dailycodingproblem-go/issues/503)
* [Day 245](https://github.com/vaskoz/dailycodingproblem-go/issues/506)
* [Day 246](https://github.com/vaskoz/dailycodingproblem-go/issues/508)
* [Day 247](https://github.com/vaskoz/dailycodingproblem-go/issues/510)
47 changes: 47 additions & 0 deletions day247/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package day247

// BinaryTree is a simple binary tree without a value.
type BinaryTree struct {
// Value int // is unnecessary. We don't need any value.
Left, Right *BinaryTree
}

// IsHeightBalanced returns true if the tree is height balanced.
// It returns false otherwise.
// Runs in O(N) time.
func IsHeightBalanced(root *BinaryTree) bool {
_, balanced := isHeightBalanced(root)
return balanced
}

func isHeightBalanced(n *BinaryTree) (int, bool) {
if n == nil {
return 0, true
}
leftHeight, leftBalance := isHeightBalanced(n.Left)
if !leftBalance {
return 0, false
}
rightHeight, rightBalance := isHeightBalanced(n.Right)
if !rightBalance {
return 0, false
}
if diff := abs(leftHeight - rightHeight); diff > 1 {
return 0, false
}
return max(leftHeight, rightHeight) + 1, true
}

func max(a, b int) int {
if a > b {
return a
}
return b
}

func abs(a int) int {
if a < 0 {
return -a
}
return a
}
74 changes: 74 additions & 0 deletions day247/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package day247

import "testing"

// nolint
var testcases = []struct {
root *BinaryTree
heightBalanced bool
}{
{
&BinaryTree{
&BinaryTree{nil, nil},
&BinaryTree{nil, nil},
},
true,
},
{
&BinaryTree{
nil,
&BinaryTree{nil, nil},
},
true,
},
{
&BinaryTree{
nil,
&BinaryTree{&BinaryTree{nil, nil}, nil},
},
false,
},
{
&BinaryTree{
nil,
&BinaryTree{
&BinaryTree{
nil,
&BinaryTree{nil, nil},
},
nil,
},
},
false,
},
{
&BinaryTree{
&BinaryTree{
nil,
&BinaryTree{
&BinaryTree{nil, nil},
nil,
},
},
nil,
},
false,
},
}

func TestIsHeightBalanced(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := IsHeightBalanced(tc.root); result != tc.heightBalanced {
t.Errorf("expected %v, got %v", tc.heightBalanced, result)
}
}
}

func BenchmarkIsHeightBalanced(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
IsHeightBalanced(tc.root)
}
}
}

0 comments on commit c774c66

Please sign in to comment.