Skip to content

Commit 5991063

Browse files
author
falldio
committed
Go for Binary Tree MAximum Path Sum
1 parent a460bb3 commit 5991063

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Trees.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -817,6 +817,39 @@ private:
817817
};
818818
```
819819
820+
```go
821+
/**
822+
* Definition for a binary tree node.
823+
* type TreeNode struct {
824+
* Val int
825+
* Left *TreeNode
826+
* Right *TreeNode
827+
* }
828+
*/
829+
func maxPathSum(root *TreeNode) int {
830+
ans := -1 << 63
831+
maxPath(root, &ans)
832+
return ans
833+
}
834+
835+
func maxPath(root *TreeNode, ans *int) int {
836+
if root == nil {
837+
return 0
838+
}
839+
leftPathSum := maxPath(root.Left, ans)
840+
rightPathSum := maxPath(root.Right, ans)
841+
*ans = max(*ans, leftPathSum + rightPathSum + root.Val)
842+
return max(max(leftPathSum+root.Val, rightPathSum+root.Val), 0)
843+
}
844+
845+
func max(a int, b int) int {
846+
if (a >= b) {
847+
return a
848+
}
849+
return b
850+
}
851+
```
852+
820853
## [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree)
821854

822855
A:

0 commit comments

Comments
 (0)