257. 二叉树的所有路径
class Solution {
public:
vector<string> ans;
vector<int> tem;
vector<vector<int>> nums;
void dfs(TreeNode* root) {
if (root->left == nullptr && root->right == nullptr) {
tem.push_back(root->val);
nums.push_back(tem);
}
else {
tem.push_back(root->val);
if (root->left != nullptr) dfs(root->left);
if (root->right != nullptr) dfs(root->right);
}
if (!tem.empty()) tem.pop_back();
}
void func() {
for (auto& i : nums) {
string s;
for (auto& j : i) {
s += to_string(j) + "->";
}
s.pop_back();
s.pop_back();
ans.push_back(s);
}
}
vector<string> binaryTreePaths(TreeNode* root) {
if (root == nullptr) return {};
dfs(root);
func();
return ans;
}
};