Skip to content

Commit

Permalink
Merge 6b1e068 into face8b7
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Jan 2, 2019
2 parents face8b7 + 6b1e068 commit c91ee10
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,4 @@ problems from
* [Day 130](https://github.com/vaskoz/dailycodingproblem-go/issues/265)
* [Day 131](https://github.com/vaskoz/dailycodingproblem-go/issues/270)
* [Day 132](https://github.com/vaskoz/dailycodingproblem-go/issues/272)
* [Day 133](https://github.com/vaskoz/dailycodingproblem-go/issues/275)
21 changes: 21 additions & 0 deletions day133/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package day133

// BST is a binary search tree of integers.
type BST struct {
Value int
Left, Right, Parent *BST
}

// InorderSuccessor returns a pointer to the next bigger element.
func InorderSuccessor(node *BST) *BST {
if node == nil {
return nil
} else if node.Right == nil {
return node.Parent
}
node = node.Right
for node.Left != nil {
node = node.Left
}
return node
}
50 changes: 50 additions & 0 deletions day133/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package day133

import "testing"

var tree = createBST()

var testcases = []struct {
givenNode, inorderSuccessor *BST
}{
{nil, nil},
{tree.Right.Left, tree.Right},
{tree, tree.Right.Left},
{tree.Left, tree},
{tree.Right, tree.Right.Right},
}

func TestInorderSuccessor(t *testing.T) {
t.Parallel()
for tcid, tc := range testcases {
if result := InorderSuccessor(tc.givenNode); result != tc.inorderSuccessor {
t.Errorf("Nodes don't match for TCID%d", tcid)
}
}
}

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

func createBST() *BST {
bst := &BST{
Value: 10,
Parent: nil,
Left: &BST{5, nil, nil, nil},
Right: &BST{
Value: 30,
Left: &BST{22, nil, nil, nil},
Right: &BST{35, nil, nil, nil},
},
}
bst.Left.Parent = bst
bst.Right.Parent = bst
bst.Right.Left.Parent = bst.Right
bst.Right.Right.Parent = bst.Right
return bst
}

0 comments on commit c91ee10

Please sign in to comment.