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

Binary Tree Maximum Path Sum

时间:2015-03-13 12:26:01      阅读:114      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!