Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1
      / \
     2   3

Return 6.

属于动态规划问题,只不过这里需要传递的数据太多,特别是递归的时候,所以定义了数组,方便在函数里来回传递,起到全局变量的作用。

一共有三种:

1,局部最大值

2,第二种类型的局部最大值

3,全局最大值

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int maxPathSum(TreeNode root) {
        int[] max = {Integer.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE};//有两种类型的局部最大值,一种是max(root.val,root.val+root.left.val,root.right.val),一种是root.left.val+root.right.val+root.val,前一种会对父节点的最大值产生影响,而后一种可能会影响全局最大值,最后一个元素是全局最大值
        inorder(root,max);
        return max[2] >= max[1]? max[2]:max[1] ;
    }
    public int inorder(TreeNode root, int[] max){
        if(root == null){
            return 0;
        }
        if(root.left == null && root.right == null){//叶子节点
            max[2] = max[2] >= root.val ? max[2] : root.val; 
            return root.val;
        }
        int left = inorder(root.left,max);
        int right = inorder(root.right,max);
        max[0] = root.val >= root.val + left ? (root.val >= root.val + right ? root.val : root.val + right ) : (left >= right ? root.val+left : root.val + right );
        max[1] = max[1] >= root.val+left+right ? max[1] : root.val+left+right;//跟新第二类型的局部最大值
        max[2] = max[2] >= max[0] ? max[2] : max[0]; //更新全局最大值
        return max[0];
    }
}
Runtime:  376 ms

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值