-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdfsUtil.h
155 lines (120 loc) · 3.23 KB
/
dfsUtil.h
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
//
// Created by ChenZhongPu on 3/31/16.
//
#ifndef MINIDFS_DFSUTIL_H
#define MINIDFS_DFSUTIL_H
#include <sstream>
#include <string>
#include <vector>
#include <utility>
#include <iostream>
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems);
std::vector<std::string> split(const std::string &s, char delim);
struct fileRange
{
long long from;
int count;
int blockId;
fileRange(long long _from, int _count, int _blockId)
{
from = _from;
count = _count;
blockId = _blockId;
}
};
class TreeNode
{
public:
std::string value;
bool isFile;
TreeNode* parent;
TreeNode* firstChild;
TreeNode* nextSibling;
TreeNode(std::string _value, bool _isFile): value(_value), isFile(_isFile), parent(nullptr), firstChild(nullptr), nextSibling(
nullptr) {}
};
class FileTree
{
public:
TreeNode *root = nullptr;
bool findNode(const std::string value, bool isFile, TreeNode*& node_parent)
{
std::vector<std::string> files = split(value, '/');
TreeNode* node = root->firstChild;
bool isFound = true;
for (int i = 0; i < files.size(); i++)
{
bool isBreakFromWhile = false;
std::string file = files[i];
bool _isFile = isFile;
if (i < files.size() - 1)
{
_isFile = false;
}
while (node != nullptr)
{
if (node->isFile == _isFile && file.compare(node->value) == 0)
{
node_parent = node;
node = node->firstChild;
isBreakFromWhile = true;
break;
}
node = node->nextSibling;
}
if (!isBreakFromWhile)
{
if (node == nullptr)
{
isFound = false;
break;
}
}
}
return isFound;
}
public:
FileTree()
{
root = new TreeNode("/", false);
}
void insertNode(const std::string value, bool isFile)
{
TreeNode *nodeParent = root;
//bool isFound = findNode(value, isFile, nodeParent);
bool isFound = findNode(value, isFile, nodeParent);
if (!isFound)
{
std::vector<std::string> files = split(value, '/');
TreeNode* newNode = new TreeNode(files.back(), isFile);
newNode->parent = nodeParent;
TreeNode *temp = nodeParent->firstChild;
if (temp == nullptr)
{
nodeParent->firstChild = newNode;
}
else
{
while (temp->nextSibling != nullptr)
{
temp = temp->nextSibling;
}
temp->nextSibling = newNode;
}
}
}
void printall(TreeNode * node)
{
if (node != nullptr)
{
std::cout << node->value << std::endl;
printall(node->nextSibling);
printall(node->firstChild);
}
}
void printall()
{
printall(root->firstChild);
}
};
#endif //MINIDFS_DFSUTIL_H