[leetcode-14]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 .
Analysis
This has two different aspects, the node value could be + or -, path could start and end at any node in the tree
A good idea found from the internet is: 1. Set one variable to store the max sum. 2. Scan every node in the tree. 3. For each node, compute the max sum of left sub tree and max sum of the right sub tree, mention that here the max sum is from the path that goes end at the left child, and start from any one of the node below the left child. (recursively) 4. Compare the max sum to the (left+right+current-val), be careful with the "-", if left<0 don't add left, same for the right. And update the max sum. For each node(sub tree), there are two status, one is the path ends at this node, the other is the path goes through this node. In the first case, the path sum is current-val+max(left_s,right_s). and the sum here can be used for the parent of this node. In the second case, just compare the sum current-val+ left_s + right_s with the current max_sum, and update the max_sum.
c++
int Getmax(TreeNode *root, int &maxCrossRoot){
        if(root == NULL) return 0;
        int left = Getmax(root->left, maxCrossRoot);
        int right = Getmax(root->right, maxCrossRoot);
        int rMax = root->val;
        
        if(left>0)
            rMax += left;
        if(right>0)
            rMax += right;
        maxCrossRoot = std::max(maxCrossRoot, rMax);
        
        return std::max(root->val, std::max(root->val+left, root->val+right));
    }
    int maxPathSum(TreeNode *root) {
        int maxCrossRoot = INT_MIN;
        int maxEndbyRoot = Getmax(root, maxCrossRoot);
        return std::max(maxEndbyRoot,maxCrossRoot);
    }

java
public class Solution {
    int max_sum;
	public int maxPathSum(TreeNode root) {
        max_sum = Integer.MIN_VALUE;
        GetMax(root);
        return max_sum;
    }
	public int GetMax(TreeNode root){
		if(root == null) return 0;
		int left = GetMax(root.left);
		int right = GetMax(root.right);
		int rMax = root.val;
		if(left>0)
			rMax+=left;
		if(right>0)
			rMax+=right;
		max_sum = Math.max(max_sum, rMax);
		return Math.max(root.val, Math.max(root.val+left, root.val+right));
	}
}

좋은 웹페이지 즐겨찾기