-
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.
- Loading branch information
Showing
3 changed files
with
65 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,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 | ||
} |
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,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) | ||
} | ||
} | ||
} |