25 二叉树中和为某一值的路径
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
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 };