-
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.
Merge pull request #80 from vaskoz/day36
Day36
- Loading branch information
Showing
3 changed files
with
58 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,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 | ||
} |
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,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) | ||
} | ||
} | ||
} |