码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-medium-Binary Tree Maximum Path Sum

时间:2016-03-15 07:28:56      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

Given a binary tree, find the maximum path sum.

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

Given the below binary tree:

  1
 / 2   3

return 6.

 

一个二叉树的最大量路径,分三种情况:

1. 在左子树

2. 在右子树

3. 包括root,左子树一部分和右子树一部分

所以需要定义一个类,用来记录不同的情况,一个int用来记录左子树/右子树的最大值,一个int用来记录任何情况下的最大值

/**
 * 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 {
    /**
     * @param root: The root of binary tree.
     * @return: An integer.
     */
     
    
    class ResultType{
        int singlePath;
        int maxPath;
        
        public ResultType(int singlePath, int maxPath){
            this.singlePath = singlePath;
            this.maxPath = maxPath;
        }
    }
    
    public ResultType helper(TreeNode root){
        if(root == null){
            return new ResultType(0, Integer.MIN_VALUE);
        }
        
        ResultType left = helper(root.left);
        ResultType right = helper(root.right);
        
        int singlePath = Math.max(left.singlePath, right.singlePath) + root.val;
        singlePath = Math.max(0, singlePath);
        
        int maxPath = Math.max(left.maxPath, right.maxPath);
        maxPath = Math.max(maxPath, left.singlePath + right.singlePath + root.val);
        
        return new ResultType(singlePath, maxPath);
    }
     
    public int maxPathSum(TreeNode root) {
        // write your code here
        return helper(root).maxPath;
    }
}

 

lintcode-medium-Binary Tree Maximum Path Sum

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5277920.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!