首页 > 其他 > 详细

Binary Tree Maximum Path Sum

时间:2015-03-13 12:25:59      阅读:314      评论:0      收藏:0      [点我收藏+]

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.

思路:

  dfs

我的代码:

技术分享
public class Solution {
    public int maxPathSum(TreeNode root) {
       if(root == null) return 0;
       helper(root);
       return max;
    }
    public int helper(TreeNode root)
    {
        if(root == null) return 0;
        if(root.left == null && root.right == null) 
        {
            max = Math.max(max,root.val);
            return root.val; 
        }
        int left = helper(root.left);
        int right = helper(root.right);
        int child = Math.max(left, right);
        int val = root.val;
        max = Math.max(Math.max(left+val+right, Math.max(val,child+val)), max);
        return Math.max(val, val+child);
    }
    private int max = Integer.MIN_VALUE;
}
View Code

学习之处:

  • max的条件略复杂,自身 or 自身+maxchild or 自身+left+right 
  • return的条件 自身 or 自身 + maxchild

Binary Tree Maximum Path Sum

原文:http://www.cnblogs.com/sunshisonghit/p/4334524.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!