题解
Easy | DFS
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> paths;
dfs(root, "", paths);
return paths;
}
void dfs(TreeNode* node, string path, vector<string>& paths) {
if(!node) return;
if(!node->left && !node->right) {
path += to_string(node->val);
paths.push_back(path);
return;
}
path += to_string(node->val) + "->";
dfs(node->left, path, paths);
dfs(node->right, path, paths);
}
};