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

124. Binary Tree Maximum Path Sum

时间:2018-12-10 13:50:35      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:sequence   one   root   The   NPU   parent   bsp   div   output   

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

  

 

124. Binary Tree Maximum Path Sum

标签:sequence   one   root   The   NPU   parent   bsp   div   output   

原文地址:https://www.cnblogs.com/ruruozhenhao/p/10095698.html

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