avatar

Catalog
二叉树中的最大路径和

解题思路

分析:计算每个节点值得贡献程度,如果贡献程度小于0,则直接舍弃。计算方式可以通过计算左子树与右子树与当前节点的和的最大值,作为贡献程度。
同时 使用全局变量,每一个节点计算得到的值进行更新,获得最大的值。

代码

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int value = Integer.MIN_VALUE;
public int maxValue(TreeNode tree){
if(tree==null){
return 0;
}
int left = Math.max(maxValue(tree.left), 0);
int right = Math.max(maxValue(tree.right), 0);
int res = Math.max(left+tree.val, right+tree.val);
value = Math.max(left+right+tree.val, value);
return res;
}
public int maxPathSum(TreeNode root) {
maxValue(root);
return value;
}
}
Author: kim yhow
Link: http://yoursite.com/2020/06/21/二叉树中的最大路径和/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
    微信
  • 支付寶
    支付寶