binary-tree-maximum-path-sum

来源:互联网 发布:网络机房维护标准 编辑:程序博客网 时间:2024/05/18 02:11

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

Return6.

包含某一节点的最小路径和分为以下几种情况:
1\只有该节点自己
2\该节点和其左子树上以左子节点为末尾节点的最大和
3\该节点和其右子树上以右子节点为末尾节点的最大和
4\该节点和左子节点和右子节点作为末尾节点的贯穿路径

利用递归,注意需要全局变量保存最大值,另外需要返回的是以该节点作为末尾节点的最大和.
一定要注意越界的问题.!!!!!!!!

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {    int maxsum;public:    int maxPathSum(TreeNode *root) {        if(root==NULL)            return INT_MIN;        maxsum=INT_MIN;        int temp=recursum(root);        return max(temp,maxsum);            }    int recursum(TreeNode *root) {        if(root->left==NULL&&root->right==NULL)        {            if(root->val>maxsum)            maxsum=root->val;            return root->val;        }        int rova=root->val;        int lh=INT_MIN;        int rh=INT_MIN;        int temp=rova;        int res=rova;        if(root->left){            lh=recursum(root->left);            temp=max(temp,lh+rova);        }        if(root->right)            {            rh=recursum(root->right);            temp=max(temp,rh+rova);        }        res=temp;        if(root->left&&root->right)            {            temp=max(temp,lh+rh+rova);        }               if(temp>maxsum)            maxsum=temp;        return res;                 }};
0 0