Skip to content

Commit

Permalink
Merge pull request #202 from vaskoz/day94
Browse files Browse the repository at this point in the history
Day94
  • Loading branch information
vaskoz committed Nov 27, 2018
2 parents 8139b2a + a2a27f5 commit da5be21
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,5 +102,6 @@ problems from
* [Day 90](https://github.com/vaskoz/dailycodingproblem-go/issues/189)
* [Day 91](https://github.com/vaskoz/dailycodingproblem-go/issues/192)
* [Day 92](https://github.com/vaskoz/dailycodingproblem-go/issues/194)
* [Day 94](https://github.com/vaskoz/dailycodingproblem-go/issues/197)
* [Day 95](https://github.com/vaskoz/dailycodingproblem-go/issues/198)
* [Day 96](https://github.com/vaskoz/dailycodingproblem-go/issues/200)
41 changes: 41 additions & 0 deletions day94/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package day94

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

// MaxPathSum returns the maximum path sum in a given
// binary tree.
func MaxPathSum(tree *BinaryTree) int {
const MinInt = -int(^uint(0)>>1) - 1
result := MinInt
maxPathSum(tree, &result)
return result
}

func maxPathSum(node *BinaryTree, res *int) int {
if node == nil {
return 0
} else if node.Left == nil && node.Right == nil {
return node.Value
}
leftSum := maxPathSum(node.Left, res)
rightSum := maxPathSum(node.Right, res)
if node.Left != nil && node.Right != nil {
*res = max(*res, leftSum+rightSum+node.Value)
return max(leftSum, rightSum) + node.Value
}
if node.Left == nil {
return rightSum + node.Value
}
return leftSum + node.Value
}

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

import "testing"

var tree = &BinaryTree{
-15,
&BinaryTree{5,
&BinaryTree{-8,
&BinaryTree{2, nil, nil},
&BinaryTree{6, nil, nil}},
&BinaryTree{1, nil, nil}},
&BinaryTree{6,
&BinaryTree{3, nil, nil},
&BinaryTree{9, nil,
&BinaryTree{0,
&BinaryTree{4, nil, nil},
&BinaryTree{-1, &BinaryTree{10, nil, nil}, nil},
},
},
},
}

func TestMaxPathSum(t *testing.T) {
t.Parallel()
result := MaxPathSum(tree)
if result != 27 {
t.Errorf("Expected 27 got %v", result)
}
}

func BenchmarkMaxPathSum(b *testing.B) {
for i := 0; i < b.N; i++ {
MaxPathSum(tree)
}
}

0 comments on commit da5be21

Please sign in to comment.