Lintcode:二叉树中的最大路径和

给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和)

样例

给出一棵二叉树:

       1
      / \
     2   3

返回 6

思路:这道题被归类到了动态规划里面,还没想清楚怎么用动态规划做,。。网上查了一下别人的做法。

计算经过节点root的最大路径时,可以这样计算:

1. 左子树的最大路径+root

2. 右子树的最大路径+root

3. root

4. 经过root的一条左右相连的路径

看到这里应该想到了分治法了,使用递归去解决。

public class maxPathSum {
    int max = Integer.MIN_VALUE;  // 1. 初始化全局最大值

    public int maxPathSum(TreeNode root) {
        // write your code here
        if(root==null){
            return 0;
        } 
        helper(root);  // 2. 调用递归函数
        return max;
    }

    public int helper(TreeNode root){
        if(root==null){
            return 0;
        }
        int leftval = helper(root.left);  // 3. 分
        int rightval = helper(root.right);
        int currentMax = root.val;        // 4. 治
        if(leftval>0){
            currentMax += leftval;
        }
        if(rightval>0){
            currentMax += rightval;
        }
        if(currentMax>max){
            max = currentMax;  // 更新全局最大值
        }

        return Math.max(root.val, Math.max(leftval+root.val, rightval+root.val)); // 返回经过root为根节点的最大路径值
    }
}

你可能感兴趣的:(动态规划,LeetCode)