您的位置:首页 > 其它

二叉树中最大路径和

2017-02-07 21:28 190 查看
分治,动态规划。

分析:最长的路径一定经过某一个点,并且以这一个点为根节点;所以可以动态遍历每一个节点,找到使路径和最大的根节点。

C++代码:

/**
* Definition of TreeNode:
* class TreeNode {
* public:
*     int val;
*     TreeNode *left, *right;
*     TreeNode(int val) {
*         this->val = val;
*         this->left = this->right = NULL;
*     }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int maxPathSum(TreeNode *root) {
if (root == NULL) {
return 0;
}
vector<int> res;
maxRoot(root,res);
int a = res[0];
for(auto i : res){
if (i > a) {
a = i;
}
}
return a;
}
void maxRoot(TreeNode * root, vector<int> &res) {
if (root == NULL ) {
return;
}
int l = maxLink(root->left);
int r = maxLink(root->right);
res.push_back(max(0,l) + max(0,r) + root->val);
maxRoot(root->left,res);
maxRoot(root->right,res);
}
int maxLink(TreeNode * root) {
if (root == NULL) {
return 0;
}
return root->val + max(0,max(maxLink(root->left),maxLink(root->right)));
}
};


看网友的更简洁的方法:

在一个函数的不断递归中处理了最后的最大值ret,还要在最后返回一root为根节点的最大的一边值。

class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int maxPathSum(TreeNode *root) {
// write your code here
int ret = INT_MIN;
onePath(root,ret);
return ret;
}
int onePath(TreeNode* root,int&ret)
{
if(root==nullptr)
return 0;
int l = onePath(root->left,ret);
int r = onePath(root->right,ret);
ret = max(ret,max(0,l)+max(0,r)+root->val);
return max(0,max(l,r))+root->val;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: