Skip to content

Commit

Permalink
Merge 5faee55 into 8b24739
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Nov 19, 2018
2 parents 8b24739 + 5faee55 commit ea6aeab
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,4 @@ problems from
* [Day 86](https://github.com/vaskoz/dailycodingproblem-go/issues/181)
* [Day 87](https://github.com/vaskoz/dailycodingproblem-go/issues/183)
* [Day 88](https://github.com/vaskoz/dailycodingproblem-go/issues/185)
* [Day 89](https://github.com/vaskoz/dailycodingproblem-go/issues/187)
24 changes: 24 additions & 0 deletions day89/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package day89

// BST represents a binary search tree.
type BST struct {
Value int
Left, Right *BST
}

// IsValidBST checks if the given tree conforms to the BST property.
func IsValidBST(root *BST) bool {
const MaxInt = int(^uint(0) >> 1)
const MinInt = -MaxInt - 1
return isValidBST(root.Left, MinInt, root.Value) && isValidBST(root.Right, root.Value, MaxInt)
}

func isValidBST(root *BST, min, max int) bool {
if root == nil {
return true
}
if root.Value > min && root.Value <= max {
return isValidBST(root.Left, min, root.Value) && isValidBST(root.Right, root.Value, max)
}
return false
}
29 changes: 29 additions & 0 deletions day89/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package day89

import "testing"

var testcases = []struct {
root *BST
isValid bool
}{
{&BST{}, true},
{&BST{10, &BST{1, nil, nil}, &BST{20, nil, nil}}, true},
{&BST{10, &BST{20, nil, nil}, &BST{1, nil, nil}}, false},
}

func TestIsValidBST(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := IsValidBST(tc.root); result != tc.isValid {
t.Errorf("Expected %v got %v", tc.isValid, result)
}
}
}

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

0 comments on commit ea6aeab

Please sign in to comment.