Binary Tree Paths LeetCode solution in C++

1
class Solution {
2
private:
3
void dfs(TreeNode *root, string s, vector<string> &ans) {
4
if (root == NULL) return;
5

6
s += (to_string(root->val));
7

8
if (root->left != NULL || root->right != NULL) s += "->";
9

10
if (root->left == NULL and root->right == NULL) {
11
ans.push_back(s);
12
}
13

14
dfs(root->left, s, ans);
15
dfs(root->right, s, ans);
16
s.pop_back();
17
}
18

19
public:
20
vector<string> binaryTreePaths(TreeNode *root) {
21
vector<string> ans;
22
string s;
23
dfs(root, s, ans);
24
return ans;
25
}
26
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0