-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} | ||
} |