import structure.TreeNode;
public class Main {
private static int res = Integer.MIN_VALUE;
public static int getMaxPathSum(TreeNode root) {
if (root == null) {
return 0;
}
dfs(root);
return res;
}
public static int dfs(TreeNode root) {
if (root == null) {
return 0;
}
int leftMax = Math.max(0, dfs(root.left)); // 左子树对最大路径和的贡献
int rightMax = Math.max(0, dfs(root.right)); // 如子树对最大路和径贡献
res = Math.max(res, root.val + leftMax + rightMax); // 当前节点的最大路劲和
return root.val + Math.max(leftMax, rightMax); // 返回当前节点的最大贡献
}
public static void main(String[] args) {
TreeNode root = new TreeNode<>(1);
root.left = new TreeNode<>(20);
root.left.left = new TreeNode<>(15);
System.out.println(getMaxPathSum(root));
}
}
二叉树中最大路径和
最新推荐文章于 2023-12-31 00:34:11 发布