二叉树中和为某一值的路径(递归&回溯)
二叉树中和为某一值的路径
https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca?tpId=13&tqId=11177&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } };*/ class Solution { public: vector<vector<int> > FindPath(TreeNode* root,int expectNumber) { if(root==NULL) { return ans; } tmp.push_back(root->val); if((root->val==expectNumber)&&(root->left==NULL)&&(root->right==NULL)) { ans.push_back(tmp); } FindPath(root->left,expectNumber-root->val); FindPath(root->right,expectNumber-root->val); if(tmp.size()!=0) { tmp.pop_back();//回溯 } return ans; } private: vector<vector<int>> ans; vector<int> tmp ; };