-
Notifications
You must be signed in to change notification settings - Fork 0
/
257. Binary Tree Paths.cpp
54 lines (49 loc) · 1.15 KB
/
257. Binary Tree Paths.cpp
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
/*
Problem Description:
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> results;
returnPaths(root,results,"");
return results;
}
void returnPaths(TreeNode* root,vector<string>& results,string temp_str)
{
if(!root)
{
return;
}
temp_str=(temp_str==""?to_string(root->val):temp_str+"->"+to_string(root->val));
if(root->left)
{
returnPaths(root->left,results,temp_str);
}
if(root->right)
{
returnPaths(root->right,results,temp_str);
}
if(!root->left && !root->right)
{
results.push_back(temp_str);
}
}
};