Fetch the repository succeeded.
//孩子兄弟表示法,将一个复杂的目录树转换为一颗二叉树
//查找某个结点的某个孩子比较便利,只需要通过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);
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。