二叉树中寻找节点和最大值的路径(C++ 实现)

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 
 // rule in result vector during iteration:
 // single path: 0;   ----> v0
 // cross path: 1;    ----> v1
 // single point: 2;  ----> v2
 // lonely path: 3;   ----> v3
 
class Solution {
public:
    int maxPathSum(TreeNode *root) {
        vector<int> *rv = mps(root);
        int r = miv(*rv);
        delete rv;
        return r;
    }
    
    vector<int> *mps(TreeNode *root) {
        if(!root) return NULL;
        
        vector<int> *ret = new vector<int>;
        
        vector<int> *lr = mps(root->left);
        vector<int> *rr = mps(root->right);
        
        vector<int> v0;
        v0.push_back(root->val);
        if(lr) v0.push_back(root->val + (*lr)[0]);
        if(rr) v0.push_back(root->val + (*rr)[0]);
        
        vector<int> v1;
        if(lr) v1.push_back((*lr)[1]);
        if(rr) v1.push_back((*rr)[1]);
        if(lr && rr) v1.push_back((*lr)[0] + (*rr)[0] + root->val);
        
        vector<int> v2;
        v2.push_back(root->val);
        if(lr) v2.push_back((*lr)[2]);
        if(rr) v2.push_back((*rr)[2]);
        
        vector<int> v3;
        if(lr) {
            v3.push_back((*lr)[0]);
            v3.push_back((*lr)[3]);
        }
        if(rr) {
            v3.push_back((*rr)[0]);
            v3.push_back((*rr)[3]);
        } 
        
        ret->push_back(miv(v0));
        ret->push_back(miv(v1));
        ret->push_back(miv(v2));
        ret->push_back(miv(v3));
        
        delete lr;
        delete rr;
        
        return ret;
    }
    
    // max in vector
    int miv(vector<int> l) {
        int m = INT_MIN;
        vector<int>::const_iterator cit = l.begin();
        while(cit != l.end()) {
            m = *cit > m ? *cit : m;
            cit ++;
        }
        return m;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值