-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path124. Binary Tree Maximum Path Sum.go
More file actions
83 lines (79 loc) · 1.56 KB
/
124. Binary Tree Maximum Path Sum.go
File metadata and controls
83 lines (79 loc) · 1.56 KB
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
package main
import "fmt"
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
type ListNode struct {
Val int
Next *ListNode
}
func buildTree(nums []int)*TreeNode{
if len(nums) == 0{
return nil
}
root := new(TreeNode)
root.Val = nums[0]
ch := make(chan *TreeNode,len(nums))
ch <- root
nums =nums[1:]
for i:=0;i<len(nums);i++{
tree := <- ch
if nums[i] == -1{
tree.Left = nil
}else{
tree.Left = &TreeNode{
Val:nums[i],
}
ch <-tree.Left
}
i++
if nums[i] == -1{
tree.Right = nil
}else{
tree.Right = &TreeNode{
Val:nums[i],
}
ch <-tree.Right
}
}
return root
}
var max int
func help(root * TreeNode){
if root == nil {
return
}
help(root.Left)
help(root.Right)
left,right,max1 := root.Val,root.Val,root.Val
if root.Left != nil &&root.Left.Val >0{
left += root.Left.Val
max1 += root.Left.Val
}
if root.Right != nil &&root.Right.Val >0{
right += root.Right.Val
max1 += root.Right.Val
}
if left > right{
root.Val = left
}else{
root.Val = right
}
if max1 > max{
max = max1
}
}
func maxPathSum(root *TreeNode) int {
if root == nil{
return 0
}
max = root.Val
help(root)
return max
}
func main(){
fmt.Println(maxPathSum(buildTree([]int{1,2,3})))
fmt.Print("Hello")
}