Binary Tree Maximum Path Sum[leet code test cases passed]

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
answer: 6 (can be any arbitary traversal path)

Consider two cases at each Node: 

1. via this node link left subtree and right subtree to find possible max sum. This node will be the root of the new path tree.

     in this case update max

2. via this node link the subtree and its parent to form a path with nodes in higher level.

    in this case return a local_max to its parent (this node must get involved in the path). The local_max has three possibilities: (1) this node + local_max of left child (2) this node + local_max of right child (3) only this node. Choose the maximum to return.

Updating max is irrelevant of where's the root of the path tree. The recursion just prints all the possible path with maximum sum on this level.


class Solution {

public:
 
    int maxPathSum(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int max=-9999;
        helper(root,max);
        return max;
    }
    
    //return local_max if this node should be linked to its parent
    int helper(TreeNode *root, int& max) 
    {
        
        if(root==NULL)
              return -9999;
        
        int sum_from_left_child = helper(root->left,max);
        int sum_from_right_child = helper(root->right,max);
        int local_max=0;
    
        //if connect root to its parent and form a new path, choose either left or right local max
        if(sum_from_left_child >= sum_from_right_child)
        {
            if(root->val < root->val + sum_from_left_child)
                 local_max=root->val + sum_from_left_child;
            else
                 local_max=root->val;     
        }
        else{
            if(root->val < root->val + sum_from_right_child)
                 local_max=root->val + sum_from_right_child;
            else
                 local_max=root->val; 
        }
        
        //update max
        if(max < sum_from_right_child + root->val + sum_from_left_child)
             max=sum_from_right_child + root->val + sum_from_left_child;
        if(max < local_max)
             max = local_max;
             
        return local_max;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值