Monday, June 17, 2013

Path Sum II (C++ code)

Leetcode Path Sum II, Oct 14 '122982 / 8423
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]
]
思路:递归。用完某个node之后记得把值pop出来。


  1. void findpath(TreeNode *root, int sum, vector<vector<int>> &res, vector<int> &path){  
  2.   
  3.   if(!root->left && !root->right){  
  4.   
  5.        if(sum == 0) res.push_back(path);  
  6.   
  7.        return;   
  8.   
  9.   }   
  10.   
  11.   if(root->left){  
  12.   
  13.     path.push_back(root->left->val);   
  14.   
  15.     findpath(root->left, sum - root->left->val, res, path);  
  16.   
  17.     path.pop_back();   
  18.   
  19.   }  
  20.   
  21.   if(root->right){   
  22.   
  23.     path.push_back(root->right->val);  
  24.   
  25.     findpath(root->right, sum - root->right->val, res, path);  
  26.   
  27.     path.pop_back();  
  28.   
  29.   }  
  30.   
  31. }   
  32.   
  33.    
  34.   
  35. vector<vector<int> > pathSum(TreeNode *root, int sum) {  
  36.         vector<vector<int>> res;  
  37.   
  38.         vector<int> path;   
  39.   
  40.         if(!root) return res;  
  41.   
  42.         path.push_back(root->val);  
  43.   
  44.         findpath(root, sum - root->val, res, path);  
  45.         return res;  
  46.     }   

No comments:

Post a Comment