Tuesday, February 3, 2015

LeetCode [124] Binary Tree Maximum Path Sum

 124. Binary Tree Maximum Path Sum

Hard

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
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//C++: 32ms
/**
 * Definition for binary tree
 * 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 ret = INT_MIN;
        dfs(root, ret);
        return ret;
    }
    int dfs(TreeNode* root, int &ret){
        if(!root) return 0;
        int l = dfs(root->left, ret);
        int r = dfs(root->right, ret);
        int len = root->val;
        if(l>0) len += l;
        if(r>0) len += r;
        ret = max(ret, len);
        return root->val+max(0, max(l, r));
    }
};

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int maxLen = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        dfs(root);
        return maxLen;
    }
    
    int dfs(TreeNode node){
        if(node==null) return 0;
        int l = dfs(node.left);
        int r = dfs(node.right);
        int len = node.val;
        if(l>0) len += l;
        if(r>0) len += r;
        maxLen = Math.max(maxLen, len);
        return node.val+Math.max(0, Math.max(l, r));
    }
}

No comments:

Post a Comment