二叉树的“路径”问题
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<string> binaryTreePaths(TreeNode* root) { //这题是要回溯的,回溯跟递归本来就是分不开的,先考虑递归参数和返回值 //递归参数,需要一个path数组,需要一个result的结果集 vector<int> path; vector<string> result; if(root == nullptr) return result; getPath(root, path, result); return result; } void getPath(TreeNode* root, vector<int>& path, vector<string>& result) { path.push_back(root->val); //递归的终止条件是什么,也就是base case //如果到了叶子节点,就需要统计路径了 if(root->left == nullptr && root->right == nullptr) {//这里没有判断当前借点是不是空节点是因为下面控制了如果为空就不进入递归 string recordPath; for(int i=0; i<path.size()-1; i++) { recordPath += to_string(path[i]); recordPath += "->"; } recordPath += to_string(path[path.size()-1]); result.push_back(recordPath); return; } if(root->left) { getPath(root->left, path, result); path.pop_back();//回溯,一次递归对应一次回溯 } if(root->right) { getPath(root->right, path, result); path.pop_back(); } } };
回溯:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> res; vector<int> path; findPath(root, sum, res, path); return res; } private: void findPath(TreeNode* root, int sum, vector<vector<int>>& res, vector<int>& path) { if (root == nullptr) return; path.push_back(root->val); sum -= root->val; if (sum == 0 && root->left == nullptr && root->right == nullptr) res.push_back(path); findPath(root->left, sum, res, path); findPath(root->right, sum, res, path); sum += root->val; path.pop_back(); } };