-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_tree_paths.cpp
More file actions
68 lines (64 loc) · 1.68 KB
/
binary_tree_paths.cpp
File metadata and controls
68 lines (64 loc) · 1.68 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
59
60
61
62
63
64
65
66
67
68
/*
* =====================================================================================
*
* Filename: binary_tree_paths.cpp
*
* Description: Binary Tree Paths.
* Given a binary tree, return all root-to-leaf paths.
*
* Version: 1.0
* Created: 02/21/19 12:30:11
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <string>
#include <vector>
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
std::vector<std::string> binaryTreePaths(TreeNode* root)
{
std::vector<std::string> paths;
binaryTreePaths(root, std::string("->"), paths);
return paths;
}
private:
void binaryTreePaths(TreeNode* node, const std::string& prefix, std::vector<std::string>& paths)
{
if (node == NULL)
{
return;
}
else if (node->left == NULL && node->right == NULL)
{
auto new_path = prefix + std::to_string(node->val);
new_path = new_path.substr(2);
paths.push_back(new_path);
}
else
{
auto new_pre = prefix + std::to_string(node->val) + "->";
binaryTreePaths(node->left, new_pre, paths);
binaryTreePaths(node->right, new_pre, paths);
}
}
};
int main(int argc, char* argv[])
{
TreeNode* root = NULL;
auto paths = Solution().binaryTreePaths(root);
return 0;
}