C++之求解二叉树中所有从根节点到叶节点的所有路径(23)---《那些奇怪的算法》

2 篇文章 0 订阅
1 篇文章 0 订阅

我们需要判断从根节点到叶节点的所有路径,并对每条路径上的节点从根节点到叶节点不断乘10操作,类似于将字符串转化为int操作,具体问题见:https://www.nowcoder.com/practice/185a87cd29eb42049132aed873273e83?tpId=46&tqId=29051&rp=1&ru=/ta/leetcode&qru=/ta/leetcode/question-ranking,下面进行求解:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int sumNumbers(TreeNode *root) {
        int allsum=0;
        vector<int> vec;
        pathvec(root,vec);
        vector<vector<int>>::iterator iter=allpaths.begin();
        while(iter!=allpaths.end()){
            allsum+=count(*iter);
            iter++;
        }
        return allsum;
    }
    int count(vector<int> vec){
        vector<int>::iterator iter=vec.begin();
        int sum=0;
        while(iter!=vec.end()){
            sum=sum*10+*iter;
            iter++;
        }
        return sum;
    }
    void pathvec(TreeNode* root,vector<int>& onepath){
        //vector<vector<int>> allpaths;
        if(root!=NULL) onepath.push_back(root->val);
        else return;
        if(root->left==NULL&&root->right==NULL) allpaths.push_back(onepath);
        if(root->left) pathvec(root->left,onepath);
        if(root->right) pathvec(root->right,onepath);
        onepath.pop_back();
    }
private:
    vector<vector<int>> allpaths;
};

需要注意的是,记得在每次添加之后需要将最后添加的pop掉,即onepath.pop_back()操作的作用,通过将每条路径添加到allpaths中就可以或者二叉树的从根节点到叶节点的所有路径!
还有一个需要解决的问题是如何不通过private结构中的allpaths结构,而是在递归的过程中将allpaths进行设置,即C思维的解决方式。。。
新的思路出现啦!!!

通过在递归的时候设置all_path参数进行更新存储即可!

class Solution {
public:
    int sumNumbers(TreeNode *root) {
        int allsum=0;
        vector<int> vec;
        vector<vector<int> >all_path;
        pathvec(root,vec,all_path);
        vector<vector<int>>::iterator iter=all_path.begin();
        while(iter!=all_path.end()){
            allsum+=count(*iter);
            iter++;
        }
        return allsum;
    }
    int count(vector<int> vec){
        vector<int>::iterator iter=vec.begin();
        int sum=0;
        while(iter!=vec.end()){
            sum=sum*10+*iter;
            iter++;
        }
        return sum;
    }
    void pathvec(TreeNode* root,vector<int> v,vector<vector<int> >& vv){
        if(root==NULL) return;
        v.push_back(root->val);
        if(root->left==NULL&&root->right==NULL) vv.push_back(v);
        if(root->left) pathvec(root->left,v,vv);
        if(root->right) pathvec(root->right,v,vv);
        v.pop_back();
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值