Sunday, March 8, 2015

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.
For example:
Given the below binary tree,
       1
      / \
     2   3
Return 6.
Solution: recursion
1) Recursively solve this problem
2) Get largest left sum and right sum
3) Compare to the stored maximum
本质是一次树的遍历,复杂度是O(n), 空间上是栈大小O(logn)
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int maxPathSum(TreeNode root) {
        if(root == null)
            return 0;
        
        int[] res = new int[1];
        res[0] = Integer.MIN_VALUE;
        helper(root, res);
        return res[0];
    }
    
    public int helper(TreeNode root, int[] res) {
        if(root == null)
            return 0;
            
        int left = helper(root.left, res);
        int right = helper(root.right, res);
        int curMax = Math.max(root.val, Math.max(left + root.val, right + root.val));
        
        //update maximum
        res[0] = Math.max(res[0], Math.max(curMax, (left + root.val + right)));
        
        //return sum of largest path of current node
        return curMax;
    }
}

No comments:

Post a Comment