先序遍历,套模版就是了,没啥可解释的。
class Solution { public: /** * * @param root TreeNode类 * @param sum int整型 * @return int整型vector<vector<>> */ vector<vector<int> > pathSum(TreeNode* root, int sum) { // write code here vector<vector<int>> res; if (!root) return res; vector<int> path; preOrder(root, res, path, sum, 0); return res; } void preOrder(TreeNode* root, vector<vector<int> > &res, vector<int> path, int sum, int current) { if (!root) return; current = current + root->val; path.push_back(root->val); if (!root->left && !root->right && sum == current) res.push_back(path); if (root->left) preOrder(root->left, res, path, sum ,current); if (root->right) preOrder(root->right, res, path, sum ,current); } };