Input a binary tree and an integer, print out all paths in the binary tree whose sum of node values is the input integer. A path is defined as a path from the root node of the tree down to the nodes passed by the leaf nodes.
C++:
1 /* 2 struct TreeNode { 3 int val; 4 struct TreeNode *left; 5 struct TreeNode *right; 6 TreeNode(int x) : 7 val(x), left(NULL), right(NULL) { 8 } 9 };*/ 10 class Solution { 11 private: 12 vector<vector<int> > res ; 13 public: 14 vector<vector<int> > FindPath(TreeNode* root,int expectNumber) { 15 vector<int> path ; 16 backtracking(root,expectNumber,path) ; 17 return res ; 18 } 19 20 void backtracking(TreeNode* root,int expectNumber,vector<int> path){ 21 if (root == NULL) 22 return ; 23 path.push_back(root->val); 24 expectNumber -= root->val ; 25 if (expectNumber == 0 && root->left == NULL && root->right == NULL){ 26 res.push_back(path) ; 27 }else{ 28 backtracking(root->left,expectNumber,path) ; 29 backtracking(root->right,expectNumber,path) ; 30 } 31 path.pop_back(); 32 } 33 };