先序遍历
class Solution { public: vector<vector<int> > FindPath(TreeNode* root,int expectNumber) { vector<vector<int> > result; if(root == NULL) return result; vector<int> path; FindPathCore(root,expectNumber,0,path,result); return result; } void FindPathCore(TreeNode* root,int expectNumber,int sum,vector<int> &path,vector<vector<int> > &result){ sum += root -> val; path.push_back(root -> val); if(sum == expectNumber && isleaf(root)){ result.push_back(path); } if(root->left != NULL) FindPathCore(root->left,expectNumber,sum,path,result); if(root->right != NULL) FindPathCore(root->right,expectNumber,sum,path,result); path.pop_back(); } bool isleaf(TreeNode* root){ if(root->left == NULL && root->right == NULL) return true; else return false; } };
vector<vector<int> > &result如果这里没有用引用,所有的返回值都为定义初始化时的空