lintcode--二叉树中的最大路径和

来源:互联网 发布:大数据怎样赚钱 编辑:程序博客网 时间:2024/05/22 08:13

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

样例

给出一棵二叉树:

       1      / \     2   3

返回 6



/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
 //一个节点线看作根节点,计算当前路径的最大值,然后看作子节点,计算当前分支的最大值,计算并返回
public class Solution {
    
    public int max ;
    public int maxPathSum(TreeNode root) {
        max = Integer.MIN_VALUE;
        if(root == null) return 0;
        maxpath(root);
        return max;
    }
    public int maxpath(TreeNode root){
        if(root == null) return 0;
        int left = 0, right = 0;
        if(root.left != null) left = Math.max(0, maxpath(root.left));
        if(root.right != null) right = Math.max(0, maxpath(root.right));
        max = Math.max(max, left + right + root.val);
        return Math.max(left, right) + root.val;
    }
}

原创粉丝点击