[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));
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值