Skip to content

Commit 06bb337

Browse files
committed
124.二叉树中的最大路径和
1 parent efd0a5a commit 06bb337

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

leetcode_Java/DoneTitle.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
121. 买卖股票的最佳时机
4747
122. 买卖股票的最佳时机 II
4848
123. 买卖股票的最佳时机 III
49+
124. 二叉树中的最大路径和
4950
130. 被围绕的区域
5051
131. 分割回文串
5152
136. 只出现一次的数字

leetcode_Java/Solution0124.java

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// 124. 二叉树中的最大路径和
2+
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* public class TreeNode {
7+
* int val;
8+
* TreeNode left;
9+
* TreeNode right;
10+
* TreeNode() {}
11+
* TreeNode(int val) { this.val = val; }
12+
* TreeNode(int val, TreeNode left, TreeNode right) {
13+
* this.val = val;
14+
* this.left = left;
15+
* this.right = right;
16+
* }
17+
* }
18+
*/
19+
20+
21+
/*
22+
递归:
23+
1、方法功能:入参是一个节点,返回该节点给父节点的贡献值
24+
2、终止条件:空节点时返回0
25+
3、单层递归逻辑:
26+
1)调用递归方法得到左节点、右节点的贡献值
27+
2)计算当前节点为路径根节点时的最大路径和,并更新最大结果。最大路径和 = 根节点值 + 左节点值 + 右节点值
28+
3)计算当前节点给父节点的贡献值,若为负数则记为0,并返回贡献值。贡献值 = max(0, 根+左, 根+右)
29+
*/
30+
class Solution {
31+
int res = Integer.MIN_VALUE;
32+
33+
public int maxPathSum(TreeNode root) {
34+
dfs(root);
35+
return res;
36+
}
37+
38+
private int dfs(TreeNode root) {
39+
if (root == null) {
40+
return 0;
41+
}
42+
int left = dfs(root.left);
43+
int right = dfs(root.right);
44+
res = Math.max(res, root.val + left + right);
45+
return Math.max(0, Math.max(root.val + left, root.val + right));
46+
}
47+
}

0 commit comments

Comments
 (0)