File tree Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Original file line number Diff line number Diff line change 46
46
121. 买卖股票的最佳时机
47
47
122. 买卖股票的最佳时机 II
48
48
123. 买卖股票的最佳时机 III
49
+ 124. 二叉树中的最大路径和
49
50
130. 被围绕的区域
50
51
131. 分割回文串
51
52
136. 只出现一次的数字
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments