我有一个树数据结构,其中父节点可以有任意数量的子节点(> = 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;
}
}
}
这适用于第一个节点但搜索在添加&gt; 1个节点后给出的结果不正确。 注意:我是c ++的新手,并不知道向量的概念。所以我必须在不使用向量的情况下这样做。此外,如果可能,U可以建议合适的结构。
答案 0 :(得分:1)
您可以考虑在指针的向量(或数组)中存储下一个指针:
class Node{
public:
string name() const {return _name;}
....
private:
string _name; //some data stored in node
vector<Node *> next; //vector of childs
};
然后在搜索方法中迭代此向量:
Node *search (string name)
{
if (_name == name)
return this;
else
for(int ix = 0; ix < next.size(); ++ix)
{
Node *temp = next[ix]->search(name);
if (temp->name() == name)
return temp;
}
return 0; //nothing found
}
}