当前位置:编程学习 > C/C++ >>

Path Sum II

Question:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
 
For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1
return
 
[
   [5,4,11,2],
   [5,8,4,5]
]
Anwser 1:     
[cpp] 
/** 
 * Definition for binary tree 
 * struct TreeNode { 
 *     int val; 
 *     TreeNode *left; 
 *     TreeNode *right; 
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 
 * }; 
 */  
class Solution {  
public:  
    void calPath(TreeNode *root, int sum, vector<int> tmp, vector< vector<int> > &ret){  
        if(root == NULL){  
            return;  
        }  
          
        tmp.push_back(root->val);  
        if(sum == root->val && root->left == NULL && root->right == NULL){  
            ret.push_back(tmp);  
        }  
          
        calPath(root->left, sum - root->val, tmp, ret);  
        calPath(root->right, sum - root->val, tmp, ret);  
          
        tmp.pop_back();  
    }  
  
    vector<vector<int> > pathSum(TreeNode *root, int sum) {  
        // Start typing your C/C++ solution below  
        // DO NOT write int main() function  
        vector< vector<int> > ret;  
          
        if(root == NULL) {  
            return ret;  
        }  
          
        vector<int> tmp;  
        calPath(root, sum, tmp, ret);  
        return ret;  
    }  
};  
 
 
Anwser 2:    
[cpp]
/** 
 * Definition for binary tree 
 * struct TreeNode { 
 *     int val; 
 *     TreeNode *left; 
 *     TreeNode *right; 
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 
 * }; 
 */  
class Solution {  
public:  
    void calPath(TreeNode *root, int sum, vector<int> tmp, vector< vector<int> > &ret){  
        if(root == NULL){  
            return;  
        }  
          
        tmp.push_back(root->val);  
        if(sum == root->val && root->left == NULL && root->right == NULL){  
            ret.push_back(tmp);  
            tmp.pop_back();     // pop tmp vector  
            return;  
        }  
          
        calPath(root->left, sum - root->val, tmp, ret);  
        calPath(root->right, sum - root->val, tmp, ret);  
          
        tmp.pop_back();  
    }  
  
    vector<vector<int> > pathSum(TreeNode *root, int sum) {  
        // Start typing your C/C++ solution below  
        // DO NOT write int main() function  
        vector< vector<int> > ret;  
          
        if(root == NULL) {  
            return ret;  
        }  
          
        vector<int> tmp;  
        calPath(root, sum, tmp, ret);  
        return ret;  
    }  
};  
 
补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,