-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathMaxPathSum.java
58 lines (49 loc) · 1.13 KB
/
MaxPathSum.java
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
package com.leetcode.hard;
import com.leetcode.base.TreeNode;
/**
*
* 给定一个非空二叉树,返回其最大路径和。
*
* 本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
*
* 示例 1:
*
* 输入: [1,2,3]
*
* 1
* / \
* 2 3
*
* 输出: 6
*
* 示例 2:
*
* 输入: [-10,9,20,null,null,15,7]
*
* -10
* / \
* 9 20
* / \
* 15 7
*
* 输出: 42
*
* */
public class MaxPathSum {
private int res = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
generatePathSum(root);
return res;
}
//定义一个辅助函数 表示以当前结点为根结点的最大路径和
private int generatePathSum(TreeNode node) {
if (node == null) {
return 0;
}
int left = Math.max(generatePathSum(node.left), 0);
int right = Math.max(generatePathSum(node.right), 0);
int sum = node.val + left + right;
res = Math.max(res, sum);
return node.val + Math.max(left, right);
}
}