二叉树中最大路径和

分治,动态规划。

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

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;  
    }  
}; 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值