Binary Tree Maximum Path Sumn

Given a 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.

For example:
Given the below binary tree,

       1
      / \
     2   3

Return 6.

分析: 这道题目采用后序遍历,但需要注意每个点都有能作为路径的“中点”,也有可能只是路径中一个普通的节点。

 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    int res =-32768;
public:
    int postorder(TreeNode* root){
        int leftsum =0,rightsum =0;
        if(root->left){
           leftsum =postorder(root->left);
        }
        if(root->right){
            rightsum = postorder(root->right);
        }
        int sum = root->val+ max(0,leftsum)+max(0,rightsum);
        res =  max(sum,res);
        sum =root->val+ max(max(0,leftsum),max(0,rightsum));
        res =  max(sum,res);
        return sum;
    }
    int maxPathSum(TreeNode* root) {
        postorder(root);
        return res;
        
      
    }
};

 

posted @ 2017-02-04 13:53  WillWu  阅读(137)  评论(0编辑  收藏  举报