输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。\
注意find中最后要pop_back()。
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 vector<vector<int> > FindPath(TreeNode* root,int expectNumber) { 13 vector<vector<int>> res; 14 if(root==NULL) 15 return res; 16 vector<int> path; 17 find(root,expectNumber,res,path); 18 return res; 19 } 20 private: 21 void find(TreeNode* root,int expectNumber,vector<vector<int>> &res,vector<int> &path){ 22 expectNumber-=root->val; 23 path.push_back(root->val); 24 if(expectNumber==0&&root->left==NULL&&root->right==NULL) 25 res.push_back(path); 26 if(root->left!=NULL) 27 find(root->left,expectNumber,res,path); 28 if(root->right!=NULL) 29 find(root->right,expectNumber,res,path); 30 path.pop_back(); 31 } 32 };
原文:http://www.cnblogs.com/zl1991/p/4768067.html