Skip to content

Commit

Permalink
Merge f0dd090 into 1e25b30
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Oct 21, 2019
2 parents 1e25b30 + f0dd090 commit 3724912
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@ problems from
* [Day 323](https://github.com/vaskoz/dailycodingproblem-go/issues/656)
* [Day 324](https://github.com/vaskoz/dailycodingproblem-go/issues/658)
* [Day 325](https://github.com/vaskoz/dailycodingproblem-go/issues/660)
* [Day 326](https://github.com/vaskoz/dailycodingproblem-go/issues/661)
* [Day 333](https://github.com/vaskoz/dailycodingproblem-go/issues/668)
* [Day 337](https://github.com/vaskoz/dailycodingproblem-go/issues/674)
* [Day 338](https://github.com/vaskoz/dailycodingproblem-go/issues/675)
Expand Down
30 changes: 30 additions & 0 deletions day326/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package day326

// IntBinaryTree is a typical binary tree
// that stores integers for a value.
type IntBinaryTree struct {
Value int
Left, Right *IntBinaryTree
}

// CartesianTree returns the corresponding Cartesian tree
// based on the given sequence.
func CartesianTree(s []int) *IntBinaryTree {
if len(s) == 0 {
return nil
}

minIndex := 0

for i := range s {
if s[i] < s[minIndex] {
minIndex = i
}
}

root := &IntBinaryTree{s[minIndex], nil, nil}
root.Left = CartesianTree(s[:minIndex])
root.Right = CartesianTree(s[minIndex+1:])

return root
}
54 changes: 54 additions & 0 deletions day326/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package day326

import (
"testing"
)

// nolint
var testcases = []struct {
seq []int
expected *IntBinaryTree
}{
{
[]int{3, 2, 6, 1, 9},
&IntBinaryTree{
1,
&IntBinaryTree{
2,
&IntBinaryTree{3, nil, nil},
&IntBinaryTree{6, nil, nil},
},
&IntBinaryTree{9, nil, nil},
},
},
}

func TestCartesianTree(t *testing.T) {
t.Parallel()

for tcid, tc := range testcases {
if result := CartesianTree(tc.seq); !equalTree(result, tc.expected) {
t.Errorf("Trees do not match for TCID%d", tcid)
}
}
}

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

func equalTree(a, b *IntBinaryTree) bool {
if a == nil && b == nil {
return true
} else if a != nil && b != nil {
return a.Value == b.Value &&
equalTree(a.Left, b.Left) &&
equalTree(a.Right, b.Right)
}

return false
}

0 comments on commit 3724912

Please sign in to comment.