LeetCode 124. 二叉树中的最大路径和

题目描述

124. 二叉树中的最大路径和

image-20230804231207274

image-20230804231214825

思路分析

image-20250510004922745

参考代码

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
}

➡️ 点击查看 Java 题解

1
write your code here
本文作者:
本文链接: https://hgnulb.github.io/blog/2025/91304980
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!