-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path257-binaryTreePaths.h
More file actions
81 lines (68 loc) · 1.42 KB
/
257-binaryTreePaths.h
File metadata and controls
81 lines (68 loc) · 1.42 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
69
70
71
72
73
74
75
76
77
78
79
80
#pragma once
#include <iostream>
#include <vector>
#include <string>
#include "TreeDefine.h"
using namespace std;
class CSolution
{
public:
CSolution();
~CSolution();
public:
vector<string> binaryTreePaths(TreeNode* root);
vector<vector<int>> binaryTreePaths_int(TreeNode* root);
private:
void help(TreeNode* root, vector<vector<int>>&res, vector<int>& tmp);
void help(TreeNode* root, vector<string>&res, string tmp);
};
CSolution::CSolution()
{
}
CSolution::~CSolution()
{
}
std::vector<std::string> CSolution::binaryTreePaths(TreeNode* root)
{
vector<string> res;
string path;
help(root, res, path);
return res;
}
std::vector<vector<int>> CSolution::binaryTreePaths_int(TreeNode* root)
{
vector<vector<int>> res;
vector<int> tmp;
help(root, res, tmp);
return res;
}
void CSolution::help(TreeNode* root, vector<vector<int>>&res, vector<int>& tmp)
{
if (root == nullptr)
return;
tmp.push_back(root->val);
if (root->left == nullptr && root->right == nullptr)
{
res.push_back(tmp);
}
help(root->left, res, tmp);
help(root->right, res, tmp);
tmp.erase(tmp.begin + tmp.size() - 1);
}
void CSolution::help(TreeNode* root, vector<string>&res, string tmp)
{
if (root == nullptr)
{
return;
}
char szbuf[10] = { 0 };
itoa(root->val, szbuf,10);
tmp += szbuf;
if (root->left == nullptr && root->right == nullptr)
{
res.push_back(tmp);
}
tmp += "->";
help(root->right, res, tmp);
help(root->left, res, tmp);
}