Skip to content

Commit 1fde807

Browse files
committed
036
1 parent 1eb664f commit 1fde807

File tree

4 files changed

+73
-3
lines changed

4 files changed

+73
-3
lines changed

README.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ make test # test all
1414

1515
## Problems
1616

17-
Number | Difficulty | Asked By
18-
--- | --- | --- |
17+
Number | Difficulty | Asked By | Title
18+
--- | --- | --- | --- |
1919
[#1](problem001) | EASY | Google
2020
[#2](problem002) | HARD | Uber
2121
[#3](problem003) | MEDIUM | Google
@@ -51,4 +51,4 @@ Number | Difficulty | Asked By
5151
[#33](problem033) | EASY | Microsoft
5252
[#34](problem034) | MEDIUM | Quora
5353
[#35](problem035) | HARD | Google
54-
54+
[#36](problem036) | MEDIUM | Dropbox | Finding the second largest node in BST

problem036/README.md

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
## Daily Coding Problem: Problem #36 [MEDIUM]
2+
3+
Good morning! Here's your coding interview problem for today.
4+
5+
This problem was asked by Dropbox.
6+
7+
Given the root to a binary search tree, find the second largest node in the tree.

problem036/problem036.go

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package problem036
2+
3+
type binarySearchTree struct {
4+
value int
5+
leftChild *binarySearchTree
6+
rightChild *binarySearchTree
7+
}
8+
9+
func NewBstNode(value int) *binarySearchTree {
10+
return &binarySearchTree{
11+
value: value,
12+
leftChild: nil,
13+
rightChild: nil,
14+
}
15+
}
16+
17+
func (root *binarySearchTree) Insert(value int) *binarySearchTree {
18+
tree := root
19+
for {
20+
if value > tree.value {
21+
if tree.rightChild == nil {
22+
tree.rightChild = NewBstNode(value)
23+
return root
24+
}
25+
tree = tree.rightChild
26+
} else {
27+
if tree.leftChild == nil {
28+
tree.leftChild = NewBstNode(value)
29+
return root
30+
}
31+
tree = tree.leftChild
32+
}
33+
}
34+
}
35+
36+
func (root *binarySearchTree) FindSecondLargest() *binarySearchTree {
37+
var parentTree *binarySearchTree
38+
tree := root
39+
for tree.rightChild != nil {
40+
parentTree = tree
41+
tree = tree.rightChild
42+
}
43+
return parentTree
44+
}

problem036/problem036_test.go

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package problem036
2+
3+
import "testing"
4+
5+
func TestBinarySearchTree_FindSecondLargest(t *testing.T) {
6+
tree := NewBstNode(10).Insert(7).Insert(5).Insert(14).Insert(9)
7+
result := tree.FindSecondLargest().value
8+
if result != 10 {
9+
t.Fail()
10+
t.Log(result)
11+
}
12+
13+
tree = NewBstNode(1).Insert(2).Insert(5).Insert(4).Insert(3).Insert(11)
14+
result = tree.FindSecondLargest().value
15+
if result != 5 {
16+
t.Fail()
17+
t.Log(result)
18+
}
19+
}

0 commit comments

Comments
 (0)