LeetCode 124. 二叉树中的最大路径和
题目描述
思路分析
参考代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func maxPathSum(root *TreeNode) int {
var res int
res = math.MinInt32
// 递归计算当前节点的最大路径和
var helper func(node *TreeNode) int
helper = func(node *TreeNode) int {
if node == nil {
return 0
}
// 递归计算左右子树的最大路径和,负值不选取
left := max(helper(node.Left), 0)
right := max(helper(node.Right), 0)
res = max(res, left+right+node.Val)
// 返回当前节点与一个子树的最大路径和
return node.Val + max(left, right)
}
helper(root)
return res
}
1
write your code here
本文作者:
HGNULB
版权声明:
本博客所有文章除特别声明外,均采用
CC BY-NC-SA 4.0
许可协议,转载请注明出处!