-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_tree_max_path_sum_test.go
103 lines (84 loc) · 2.32 KB
/
binary_tree_max_path_sum_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
Problem:
- Given a binary tree, find the maximum path sum.
Assumption:
- The path might start and end at any node in the tree.
- Assume the tree is non-empty.
- The node can contain negative number.
- The maximum path does not have to go though the root node.
Approach:
- At each node, the potential maximum path could be one of these cases:
- max(left subtree) + node
- max(right subtree) + node
- max(left subtree) + max(right subtree) + node
- the node itself
Cost:
- O(n) time, O(n) space.
*/
package leetcode
import (
"math"
"testing"
"github.com/pcaruana/algo/common"
)
func TestGetMaxPathSum(t *testing.T) {
// define test cases' input.
t1 := &common.TreeNode{nil, 1, nil}
t2 := &common.TreeNode{nil, 1, nil}
t2.Right = &common.TreeNode{nil, 2, nil}
t3 := &common.TreeNode{nil, 1, nil}
t3.Left = &common.TreeNode{nil, 2, nil}
t4 := &common.TreeNode{nil, 5, nil}
t4.Left = &common.TreeNode{nil, 3, nil}
t4.Right = &common.TreeNode{nil, 8, nil}
t5 := &common.TreeNode{nil, 5, nil}
t5.Left = &common.TreeNode{nil, 3, nil}
t5.Right = &common.TreeNode{nil, 8, nil}
t5.Right.Left = &common.TreeNode{nil, 7, nil}
t5.Right.Right = &common.TreeNode{nil, 9, nil}
t6 := &common.TreeNode{nil, 5, nil}
t6.Left = &common.TreeNode{nil, 3, nil}
t6.Left.Left = &common.TreeNode{nil, 2, nil}
t6.Left.Left.Left = &common.TreeNode{nil, 1, nil}
t6.Left.Right = &common.TreeNode{nil, 4, nil}
t6.Right = &common.TreeNode{nil, 8, nil}
t6.Right.Left = &common.TreeNode{nil, 7, nil}
t6.Right.Right = &common.TreeNode{nil, 9, nil}
t6.Right.Right.Right = &common.TreeNode{nil, 11, nil}
tests := []struct {
in *common.TreeNode
expected int
}{
{t1, 1},
{t2, 3},
{t3, 3},
{t4, 13},
{t5, 22},
{t6, 33},
}
for _, tt := range tests {
common.Equal(
t,
tt.expected,
getMaxPathSum(tt.in),
)
}
}
// FIXME - need to look at this again to understand it and explain it better.
func getMaxPathSum(t *common.TreeNode) int {
max := math.MinInt64
if t == nil {
return 0
}
leftMax := getMaxPathSum(t.Left)
rightMax := getMaxPathSum(t.Right)
max = common.Max(t.Value+leftMax+rightMax, max)
m := common.Max(leftMax, rightMax)
// s is the maximum path sum that goes through the current node and to
// one if its left or right subtree to its parents.
s := t.Value + m
if s > 0 {
return s
}
return 0
}