我有一个树数据结构,其中父节点可以有任意数量的子节点(> = 0)。我想创建这样的树。我想到的一种可能的方法是创建一个链表,如 my_approach 图片所示。链表如图所示连接。
你也可以建议替代方法
所以我写了一个代码在树中搜索。(对不起,长代码)
class node
{ public:
node* boss;
string name;
node* next;
int level;
node* next_level;
node* search(string);
node() : boss(NULL), next(NULL), next_level(NULL){ }
friend class my_tree;
};
node* ans=NULL;
class my_tree
{
public:
my_tree();
void print(node*);
node* search(string,node*);
node* gethead();
bool is_empty();
void add(string, node*);
node* head;
};
my_tree::my_tree()
{
head=new node;
head->boss=NULL;
head->name="";
head->next=NULL;
head->level=0;
head->next_level=NULL;
}
bool my_tree::is_empty()
{
if(head->next_level==NULL)
{return 1;}
else if(head->next_level!=NULL)
{return 0;}
}
node* my_tree::gethead()
{
return head;
}
node* my_tree::search(string employee, node* ptr)
{
cout<<"ptr="<<ptr<<endl;
if (ptr==NULL)
{return NULL;}
else if(ptr->name==employee)
{cout<<"yup"<<endl;
ans=ptr;
return ptr;}
else if(ptr->name!=employee)
{
search(employee, ptr->next_level);
search(employee, ptr->next);
cout<<"in search ans : "<<ans<<endl;
return ans;
}
}
void my_tree::add(string employee, node* immediate_boss)
{
node* temp;
temp=new node;
temp->name=employee;
if(immediate_boss->next_level==NULL)
{
temp->boss=immediate_boss;
temp->level=immediate_boss->level+1;
immediate_boss->next_level=temp;
}
else if(immediate_boss->next_level!=NULL)
{node* ptr=immediate_boss->next_level;
while(ptr->next!=NULL)
{ptr=ptr->next;}
temp->boss=immediate_boss;
temp->level=immediate_boss->level+1;
ptr->next=temp;
}
cout<<"employee added:"<<temp->name<<" at "<<temp<<endl;
}
main()
{
my_tree Company;
char a;
string line1;
string line2;
a=myfile.get();
bool e;
cout<<"head : "<<Company.gethead()<<endl;
while(myfile.good() and myfile.is_open())
{
//I do some operations and get line2 and line1
//search functions searches for element( here I called employee) and gives its pointer. I use this pointer to add line1 as child node of line2.
Company.add(line2,Company.search(line2,Company.gethead()));
line1.clear();
line2.clear();
ans=NULL;
}
}
}
这适用于第一个节点,但在添加 >1 个节点后搜索会给出不正确的结果。注意:我是 C++ 新手,不知道向量的概念。所以我必须在不使用向量的情况下做到这一点。此外,如果可能,U 可以建议合适的结构。