Skip to content

Commit

Permalink
Merge pull request #80 from vaskoz/day36
Browse files Browse the repository at this point in the history
Day36
  • Loading branch information
vaskoz committed Sep 27, 2018
2 parents 73dbe3e + 30e7fb4 commit 6876685
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,4 @@ problems from
* [Day 31](https://github.com/vaskoz/dailycodingproblem-go/issues/71)
* [Day 33](https://github.com/vaskoz/dailycodingproblem-go/issues/73)
* [Day 35](https://github.com/vaskoz/dailycodingproblem-go/issues/77)
* [Day 36](https://github.com/vaskoz/dailycodingproblem-go/issues/79)
29 changes: 29 additions & 0 deletions day36/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package day36

// BST represents a binary search tree.
type BST struct {
val int
left, right *BST
}

// SecondLargest takes the root of a binary search tree and returns the
// pointer to the 2nd largest value.
// Runs in O(height) and O(1) space.
func SecondLargest(root *BST) int {
var prev, cur *BST
if root.right != nil {
prev = root
cur = root.right
for cur.right != nil {
cur = cur.right
prev = prev.right
}
cur = prev
} else {
cur = root.left
for cur.right != nil {
cur = cur.right
}
}
return cur.val
}
28 changes: 28 additions & 0 deletions day36/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package day36

import "testing"

var testcases = []struct {
root *BST
expected int
}{
{&BST{10, nil, &BST{20, nil, &BST{30, nil, nil}}}, 20},
{&BST{10, &BST{5, nil, &BST{8, nil, nil}}, nil}, 8},
}

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

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

0 comments on commit 6876685

Please sign in to comment.