【剑指offer-解题系列(24)】二叉树中和为某一值

来源:互联网 发布:淘宝运营规则是什么 编辑:程序博客网 时间:2024/06/09 19:17

题目描述

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

分析

深度搜索遍历,直到到达叶节点,然后统计出和。

代码实现

    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {

        vector<vector<int> >res;
        
        vector<int>path;
        
        int current_num = 0;
        getpath( root, expectNumber,res,path,current_num);
        
        return res;
      
  }
    
    
    void getpath(TreeNode* root,int expectNumber,vector<vector<int>>&res,vector<int> path,
                int current_num){
        if(root==NULL)
            return;
        
        current_num +=root->val;
        if(current_num>expectNumber){
            return;
        }
        path.push_back(root->val);
      
        if(root->left==NULL&&root->right==NULL){
            if(current_num==expectNumber){
                res.push_back(path);
            }
        }
        
        if(root->left!=NULL){
            getpath( root->left, expectNumber,res,path,current_num);
        }
        if(root->right!=NULL){
        getpath( root->right, expectNumber ,res,path,current_num);
        }
    }

阅读全文
0 0