请利用树形数据结构实现一个五级目录,并随机输出一个五级目录c++
时间: 2024-05-10 07:16:40 浏览: 50
以下是使用C++的树形数据结构实现五级目录的代码示例:
```cpp
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <ctime>
struct Node {
std::string name;
std::vector<Node*> children;
Node(const std::string& name) : name(name) {}
~Node() {
for (auto child : children) {
delete child;
}
}
};
void printTree(Node* node, int level) {
for (int i = 0; i < level; i++) {
std::cout << " ";
}
std::cout << "- " << node->name << std::endl;
for (auto child : node->children) {
printTree(child, level + 1);
}
}
int main() {
srand(time(nullptr));
Node* root = new Node("Root");
for (int i = 1; i <= 5; i++) {
Node* node1 = new Node("Level 1_" + std::to_string(i));
root->children.push_back(node1);
for (int j = 1; j <= 5; j++) {
Node* node2 = new Node("Level 2_" + std::to_string(i) + "_" + std::to_string(j));
node1->children.push_back(node2);
for (int k = 1; k <= 5; k++) {
Node* node3 = new Node("Level 3_" + std::to_string(i) + "_" + std::to_string(j) + "_" + std::to_string(k));
node2->children.push_back(node3);
for (int l = 1; l <= 5; l++) {
Node* node4 = new Node("Level 4_" + std::to_string(i) + "_" + std::to_string(j) + "_" + std::to_string(k) + "_" + std::to_string(l));
node3->children.push_back(node4);
for (int m = 1; m <= 5; m++) {
Node* node5 = new Node("Level 5_" + std::to_string(i) + "_" + std::to_string(j) + "_" + std::to_string(k) + "_" + std::to_string(l) + "_" + std::to_string(m));
node4->children.push_back(node5);
}
}
}
}
}
std::cout << "Random directory: ";
Node* node = root;
for (int i = 1; i <= 5; i++) {
int index = rand() % node->children.size();
node = node->children[index];
std::cout << node->name << "/";
}
std::cout << std::endl;
printTree(root, 0);
delete root;
return 0;
}
```
在这个代码示例中,我们定义了一个 `Node` 结构体来表示树中的每个节点。每个节点包含一个名称和一个子节点列表。我们使用循环嵌套来构建五级目录,每个级别有五个选项。对于随机输出五级目录的部分,我们从根节点开始,随机选择每个级别的一个子节点,并将其名称添加到输出字符串中,直到达到第五级为止。最后,我们调用 `printTree` 函数来打印整个目录树。
以下是一次运行程序的输出示例:
```
Random directory: Level 1_4/Level 2_4_1/Level 3_4_1_2/Level 4_4_1_2_5/Level 5_4_1_2_5_1/
- Root
- Level 1_1
- Level 2_1_1
- Level 3_1_1_1
- Level 4_1_1_1_1
- Level 5_1_1_1_1_1
- Level 4_1_1_1_2
- Level 5_1_1_1_2_1
- Level 4_1_1_1_3
- Level 5_1_1_1_3_1
- Level 4_1_1_1_4
- Level 5_1_1_1_4_1
- Level 4_1_1_1_5
- Level 5_1_1_1_5_1
- Level 3_1_1_2
- Level 4_1_1_2_1
- Level 5_1_1_2_1_1
- Level 4_1_1_2_2
- Level 5_1_1_2_2_1
- Level 4_1_1_2_3
- Level 5_1_1_2_3_1
- Level 4_1_1_2_4
- Level 5_1_1_2_4_1
- Level 4_1_1_2_5
- Level 5_1_1_2_5_1
- ...
```
可以看到,代码成功地创建了五级目录,并随机输出了一个五级目录名称。
阅读全文