-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathbinary-tree-paths(AC).cpp
More file actions
58 lines (54 loc) · 1.38 KB
/
binary-tree-paths(AC).cpp
File metadata and controls
58 lines (54 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <string>
#include <vector>
using namespace std;
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
*/
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> ans;
if (root == NULL) {
return ans;
}
vector<int> path;
path.push_back(root->val);
DFS(root, path, ans);
path.pop_back();
return ans;
}
protected:
void DFS(TreeNode *root, vector<int> &path, vector<string> &ans) {
if (root->left == NULL && root->right == NULL) {
string s = to_string(path[0]);
for (int i = 1; i < path.size(); ++i) {
s += "->" + to_string(path[i]);
}
ans.push_back(s);
return;
}
if (root->left != NULL) {
path.push_back(root->left->val);
DFS(root->left, path, ans);
path.pop_back();
}
if (root->right != NULL) {
path.push_back(root->right->val);
DFS(root->right, path, ans);
path.pop_back();
}
}
};