Path SumII

回溯

    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        vector<vector<int>> res;
        if(!root)
            return res;
        vector<int> path;
        
        dfs(root,sum,path,res);
        return res;
    }
    
    void dfs(TreeNode* root,int sum,vector<int>& path,vector<vector<int>>& res)
    {
        path.push_back(root->val);
        sum-=root->val;
        if(!root->left&&!root->right)
        {
            if(sum==0)
                res.push_back(path);
        }else
        {
            if(root->left)
                dfs(root->left,sum,path,res);
            if(root->right)
                dfs(root->right,sum,path,res);
        }
        path.pop_back();
    }

  

posted @ 2013-10-08 09:16  summer_zhou  阅读(143)  评论(0)    收藏  举报