1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
class Solution { public: vector<vector<int>> FindPath(TreeNode* root, int target) { if (root == nullptr) return vector<vector<int>> {};
vector<vector<int>> res; vector<int> path; FindPathCore(res, path, root, target); sort(res.begin(), res.end(), [](const vector<int>& a, const vector<int>& b) { return a.size() > b.size(); });
return res; }
void FindPathCore(vector<vector<int>>& res, vector<int>& path, TreeNode* node, int sum) { if (node == nullptr) return;
path.push_back(node->val); if (node->left == nullptr && node->right == nullptr && node->val == sum) { res.push_back(path); }
FindPathCore(res, path, node->left, sum - node->val); FindPathCore(res, path, node->right, sum - node->val); path.pop_back(); } };
class Solution { public: struct Compare { bool operator()(vector<int>& a, vector<int>& b) { return a.size() > b.size(); } };
vector<vector<int>> FindPath(TreeNode* root, int target) { if (root == nullptr) return {};
vector<vector<int>> res; vector<int> path; FindPathCore(res, path, root, target); sort(res.begin(), res.end(), Compare());
return res; }
void FindPathCore(vector<vector<int>>& res, vector<int> path, TreeNode* node, int sum) { if (node == nullptr) return;
path.push_back(node->val); if (node->left == nullptr && node->right == nullptr && node->val == sum) { res.push_back(path); }
FindPathCore(res, path, node->left, sum - node->val); FindPathCore(res, path, node->right, sum - node->val); path.pop_back(); } };
|