124. Binary Tree Maximum Path Sum

Given a non-empty binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

Example 1:

Input: [1,2,3]

       1
      / \
     2   3

Output: 6

Example 2:

Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42

 

Approach #1: C++.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxPathSum(TreeNode* root) {
        if (!root) return 0;
        int ans = INT_MIN;
        solve(root, ans);
        return ans;
    }
private:
    int solve(TreeNode* root, int& ans) {
        if (!root) return 0;
        int l = max(0, solve(root->left, ans));
        int r = max(0, solve(root->right, ans));
        int sum = l + r + root->val;
        ans = max(ans, sum);
        return max(l, r) + root->val;
    }
};

  

Approach #2: Java.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int ans = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        if (root == null) return 0;
        solve(root);
        return ans;
    }
    
    private int solve(TreeNode root) {
        if (root == null) return 0;
        int l = Math.max(0, solve(root.left));
        int r = Math.max(0, solve(root.right));
        int sum = l + r + root.val;
        ans = Math.max(ans, sum);
        return Math.max(l, r) + root.val;
    }
}

  

Approach #3: Python.

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def solve(self, root):
        if not root: return 0
        l = max(0, self.solve(root.left))
        r = max(0, self.solve(root.right))
        self.ans = max(self.ans, l + r + root.val)
        return max(l, r) + root.val
    
    def maxPathSum(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0
        self.ans = -sys.maxint
        self.solve(root)
        return self.ans

  

 

posted @ 2018-12-10 12:05  Veritas_des_Liberty  阅读(190)  评论(0编辑  收藏  举报