Skip to content

Commit

Permalink
Merge pull request #234 from vaskoz/day110
Browse files Browse the repository at this point in the history
Day110
  • Loading branch information
vaskoz committed Dec 12, 2018
2 parents db67db0 + 8db023f commit e1d2575
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,4 +119,5 @@ problems from
* [Day 107](https://github.com/vaskoz/dailycodingproblem-go/issues/225)
* [Day 108](https://github.com/vaskoz/dailycodingproblem-go/issues/227)
* [Day 109](https://github.com/vaskoz/dailycodingproblem-go/issues/229)
* [Day 110](https://github.com/vaskoz/dailycodingproblem-go/issues/231)
* [Day 111](https://github.com/vaskoz/dailycodingproblem-go/issues/232)
32 changes: 32 additions & 0 deletions day110/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package day110

// IntBinaryTree is a binary tree with values that are integers.
type IntBinaryTree struct {
Value int
Left, Right *IntBinaryTree
}

// AllPathsToLeaves return the nodes encountered from the root
// to each leave.
func AllPathsToLeaves(tree *IntBinaryTree) [][]int {
return pathHolder(tree, []int{})
}

func pathHolder(tree *IntBinaryTree, path []int) [][]int {
path = append(path, tree.Value)
if tree.Left == nil && tree.Right == nil {
leavePath := make([]int, len(path))
copy(leavePath, path)
return [][]int{leavePath}
}
var result [][]int
if tree.Left != nil {
leftSubtree := pathHolder(tree.Left, path)
result = append(result, leftSubtree...)
}
if tree.Right != nil {
rightSubtree := pathHolder(tree.Right, path)
result = append(result, rightSubtree...)
}
return result
}
35 changes: 35 additions & 0 deletions day110/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package day110

import (
"reflect"
"testing"
)

var testcases = []struct {
head *IntBinaryTree
expected [][]int
}{
{&IntBinaryTree{Value: 1,
Left: &IntBinaryTree{2, nil, nil},
Right: &IntBinaryTree{3,
&IntBinaryTree{4, nil, nil},
&IntBinaryTree{5, nil, nil}}},
[][]int{{1, 2}, {1, 3, 4}, {1, 3, 5}}},
}

func TestAllPathsToLeaves(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := AllPathsToLeaves(tc.head); !reflect.DeepEqual(tc.expected, result) {
t.Errorf("Expected %v got %v", tc.expected, result)
}
}
}

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

0 comments on commit e1d2575

Please sign in to comment.