1 Star 0 Fork 0

付峻霖/数据结构

Create your Gitee Account
Explore and code with more than 14 million developers,Free private repositories !:)
Sign up
文件
This repository doesn't specify license. Please pay attention to the specific project description and its upstream code dependency when using it.
Clone or Download
目录树 3.28 KB
Copy Edit Raw Blame History
付峻霖 authored 2021-05-13 09:13 +08:00 . update 目录树.
//孩子兄弟表示法,将一个复杂的目录树转换为一颗二叉树
//查找某个结点的某个孩子比较便利,只需要通过firstchild找到此结点的长子,
//然后再通过长子结点的rightsib找到它的二弟,接着一直下去,直到找到具体的孩子
#include <iostream>
#include <string>
#include <math.h>
#include <queue>
using namespace std;
/*树的孩子兄弟表示法结构定义*/
typedef struct CSNode
{
string data; //数据域
struct CSNode* firstchild; //指向对应长子结点的指针域
struct CSNode* rightsib; //指向对应右兄弟结点的指针域
int flag_file; //判断是文件还是目录的 flag
}CSNode, * CSTree;
CSTree insertNode(CSTree t, string str, int flag)
{
CSTree a_node = new CSNode;
CSTree pre = t, ptr;
a_node->data = str; //初始化新结点
a_node->firstchild = a_node->rightsib = NULL;
a_node->flag_file = flag;
if (t->firstchild == NULL) //所在目录没孩子,直接插入结点
{
t->firstchild = a_node;
return t->firstchild;
}
ptr = t->firstchild;
while (ptr != NULL && ((ptr->flag_file > a_node->flag_file) || (ptr->flag_file == a_node->flag_file && str > ptr->data)))
{
pre = ptr;
ptr = ptr->rightsib;
}
if (ptr == NULL) //无处可插入,插在链尾
{
a_node->rightsib = pre->rightsib;
pre->rightsib = a_node;
return a_node; //接下来以 a_node 为根目录操作
}
else if (ptr->data == a_node->data && ptr->flag_file == a_node->flag_file)
{
delete a_node;
return ptr;
}
else //找到了应该插入的位置
{
if (pre->data == t->data) //插在根目录的长子位
{
a_node->rightsib = pre->firstchild;
pre->firstchild = a_node;
}
else //正常插入
{
a_node->rightsib = pre->rightsib;
pre->rightsib = a_node;
}
return a_node; //接下来以 a_node 为根目录操作
}
}
void createTree(CSTree pre, string str)
{
int idx = 0;
getline(cin, str);
for (int i = 0; i < str.size(); i++)
{
if (str[i] == '\\')
{
pre = insertNode(pre, str.substr(idx, i - idx), 1);
idx = i + 1;
}
}
if (idx < str.size()) //文件只出现在字符串尾
{
pre = insertNode(pre, str.substr(idx, str.size() - idx), 0);
}
}
void PreOrderTraverse(CSTree T, int space)
{
if (T == NULL)
return;
/* 控制空格输出 */
for (int i = 0; i < space; i++)
{
cout << " ";
}
cout << T->data << endl; //前序遍历
PreOrderTraverse(T->firstchild, space + 2); //下一层多两个空格
PreOrderTraverse(T->rightsib, space); //兄弟结点不需要多空格
}
int main()
{
int num;
string str;
CSTree t = new CSNode;
t->data = "root";
t->firstchild = t->rightsib = NULL;
t->flag_file = 1;
cin >> num;
for (int i = 0; i <= num; i++)
{
createTree(t, str);
}
PreOrderTraverse(t, 0);
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/fujunlin/data-structure.git
git@gitee.com:fujunlin/data-structure.git
fujunlin
data-structure
数据结构
master

Search