LeetCode 124. Binary Tree Maximum Path Sum(二叉树最大路径和)

52 篇文章 1 订阅
49 篇文章 0 订阅

原题网址:https://leetcode.com/problems/binary-tree-maximum-path-sum/

Given a binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.

For example:
Given the below binary tree,

       1
      / \
     2   3

Return 6.

方法:分治策略,动态规划。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
//  这是我根据网上的例子,自己重写的
    private int max;
    private int maxSideSum(TreeNode root) {
        if (root == null) return 0;
        int left = maxSideSum(root.left);
        int right = maxSideSum(root.right);
        int v = left + root.val + right;
        if (v > max) max = v;
        int sum = root.val;
        if (root.val+left>sum) sum = root.val+left;
        if (root.val+right>sum) sum = root.val+right;
        if (sum>max) max = sum;
        return sum;
    }
    public int maxPathSum(TreeNode root) {
        if (root == null) return 0;
        max = root.val;
        maxSideSum(root);
        return max;
    }
    
//  这是网上搜索的解决方案,非常简洁
//  http://www.programcreek.com/2013/02/leetcode-binary-tree-maximum-path-sum-java/
}

更简洁的版本:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private int max = Integer.MIN_VALUE;
    private int maxSideSum(TreeNode node) {
        if (node == null) return 0;
        int left = maxSideSum(node.left);
        int right = maxSideSum(node.right);
        max = Math.max(max, left + node.val + right);
        return Math.max(0, node.val + Math.max(left, right));
    }
    public int maxPathSum(TreeNode root) {
        maxSideSum(root);
        return max;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值