Skip to content

Commit

Permalink
Merge ae5c3d7 into 41cc56e
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Jan 4, 2019
2 parents 41cc56e + ae5c3d7 commit 0a88a8b
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,3 +143,4 @@ problems from
* [Day 132](https://github.com/vaskoz/dailycodingproblem-go/issues/272)
* [Day 133](https://github.com/vaskoz/dailycodingproblem-go/issues/275)
* [Day 134](https://github.com/vaskoz/dailycodingproblem-go/issues/278)
* [Day 135](https://github.com/vaskoz/dailycodingproblem-go/issues/280)
30 changes: 30 additions & 0 deletions day135/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package day135

// BinaryTree is a binary tree.
type BinaryTree struct {
Value int
Left, Right *BinaryTree
}

// MinPathSum returns the sum of the minimum sum path from root to leaf.
func MinPathSum(head *BinaryTree) int {
if head.Left == nil && head.Right == nil {
return head.Value
}
if head.Left != nil && head.Right != nil {
left := head.Value + MinPathSum(head.Left)
right := head.Value + MinPathSum(head.Right)
return min(left, right)
} else if head.Left != nil {
return head.Value + MinPathSum(head.Left)
} else {
return head.Value + MinPathSum(head.Right)
}
}

func min(a, b int) int {
if a < b {
return a
}
return b
}
34 changes: 34 additions & 0 deletions day135/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package day135

import "testing"

var testcases = []struct {
tree *BinaryTree
minSum int
}{
{&BinaryTree{10,
&BinaryTree{5, nil, &BinaryTree{2, nil, nil}},
&BinaryTree{5, nil, &BinaryTree{1, &BinaryTree{-1, nil, nil}, nil}},
}, 15},
{&BinaryTree{10,
&BinaryTree{5, nil, &BinaryTree{1, &BinaryTree{-1, nil, nil}, nil}},
&BinaryTree{5, nil, &BinaryTree{2, nil, nil}},
}, 15},
}

func TestMinPathSum(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := MinPathSum(tc.tree); result != tc.minSum {
t.Errorf("Expected %v got %v", tc.minSum, result)
}
}
}

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

0 comments on commit 0a88a8b

Please sign in to comment.