Binary Tree Maximum Path Sum

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
原文地址:https://www.cnblogs.com/sunshisonghit/p/4334524.html