目录
代码(二刷自解 2024年5月9日 10min bugfree)
题目:
代码(首刷看解析 2024年1月30日):
class Solution {
public:
void recursion(TreeNode* root, vector<int>& path, vector<string>& res) {
path.push_back(root->val);
if (root->left == nullptr && root->right == nullptr) {
string spath;
for (int i = 0; i < path.size() - 1; ++i) {
spath += to_string(path[i]);
spath += "->";
}
spath += to_string(path[path.size() - 1]);
res.push_back(spath);
}
if (root->left) {
recursion(root->left,path,res);
path.pop_back();
}
if (root->right) {
recursion(root->right,path,res);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<int> path;
vector<string> res;
recursion(root,path,res);
return res;
}
};
代码(二刷自解 2024年5月9日 10min bugfree)
class Solution {
public:
// 递归 + 回溯
vector<string> res;
void recursion(TreeNode* root, string& path) {
if (!root->left && !root->right) {
res.push_back(path);
return;
}
// 前序
string temp = path;
if (root->left) {
path += "->";
path += to_string(root->left->val);
recursion(root->left, path);
path = temp;
}
if (root->right) {
path += "->";
path += to_string(root->right->val);
recursion(root->right, path);
path = temp;
}
}
vector<string> binaryTreePaths(TreeNode* root) {
res.clear();
if (!root) return res;
string path = to_string(root->val);
recursion(root, path);
return res;
}
};