码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树中和为某一值的路径

时间:2017-02-27 23:09:43      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:treenode   span   number   path   root   style   tor   int   val   

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/
class Solution {
public:
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        vector<vector<int>> res;
        if(root == NULL)
            return res;
        
        vector<int> path;
        int currentSum = 0;
        FindPath_(root,expectNumber,path,currentSum,res);
        return  res;
    }
    
    void FindPath_(TreeNode* root,int expectNumber,vector<int> &path,int currentNum,vector<vector<int>> &res){
        currentNum += root->val;
        path.push_back(root->val);
        
        bool isLeaf = root->left == NULL && root->right == NULL;
        if(currentNum == expectNumber && isLeaf){
            res.push_back(path);
        }
        
        if(root->left != NULL){
            FindPath_(root->left,expectNumber,path,currentNum,res);
        }
        if(root->right != NULL){
            FindPath_(root->right,expectNumber,path,currentNum,res);
        }
        
        currentNum -= root->val;
        path.pop_back();

    }
};

 

二叉树中和为某一值的路径

标签:treenode   span   number   path   root   style   tor   int   val   

原文地址:http://www.cnblogs.com/xiuxiu55/p/6476564.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!