30 Day Challenge Day 15 | Leetcode 257. Binary Tree Paths
题解
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);
}
};