题目描述
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
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 public: 12 void DFS(TreeNode* root,int expectNumber,int& sum,vector<vector<int> >& result,vector<int>& road) 13 { 14 sum += root->val; 15 road.push_back(root->val); 16 if(root->left == NULL && root->right == NULL && sum == expectNumber) 17 { 18 result.push_back(road); 19 } 20 if (root->left != NULL) 21 { 22 DFS(root->left,expectNumber,sum,result,road); 23 } 24 if(root->right != NULL) 25 { 26 DFS(root->right,expectNumber,sum,result,road); 27 } 28 sum -= root->val; 29 road.pop_back(); 30 } 31 vector<vector<int> > FindPath(TreeNode* root,int expectNumber) { 32 vector<vector<int> > result; 33 if(root == NULL) 34 return result; 35 vector<int> road; 36 int sum = 0; 37 DFS(root,expectNumber,sum,result,road); 38 return result; 39 } 40 41 };