Skip to content

Commit fa374ae

Browse files
authored
binary tree maximum path sum solution
1 parent d128b77 commit fa374ae

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* type TreeNode struct {
4+
* Val int
5+
* Left *TreeNode
6+
* Right *TreeNode
7+
* }
8+
*/
9+
func maxPathSum(root *TreeNode) int {
10+
ans, _ := solve(root)
11+
return ans
12+
}
13+
14+
func solve(root *TreeNode) (int, int) {
15+
if root == nil {
16+
return -30_000_000, -30_000_000
17+
}
18+
leftAns, leftRootAns := solve(root.Left)
19+
rightAns, rightRootAns := solve(root.Right)
20+
rootAns := root.Val + max(0, leftRootAns, rightRootAns,)
21+
ans := max(leftAns, rightAns, root.Val + max(0, leftRootAns,) + max(0, rightRootAns,))
22+
return ans, rootAns
23+
}

0 commit comments

Comments
 (0)