在c++中用类实现树
Implementation of tree with classes in c++
我正在尝试实现一棵树,该树在给定节点处存储子向量。我已经实现了查找节点的 find_index
函数。它有两个参数:Node * cur
和一些 key
。我在处理 insert
时尝试使用此功能,但我不知道要搜索什么 Node*
。这样的节点肯定是存在的,但是不知道用哪个来调用find_index
。我也不知道我的功能是否正常工作。提前致谢。
#include <iostream>
#include <vector>
using namespace std;
class Node{
public:
Node *parent;
vector < Node* > children;
string key;
Node(){
parent=NULL;
}
};
class tree{
public:
int size;
tree(){
size=0;
}
Node* find_index(Node *cur,string key){
Node *tmp;
if(cur->key==key){
tmp=cur;
}
if(cur==NULL){
tmp=NULL;
}
for(int i=0;i<cur->children.size();i++){
find_index(cur->children[i],key);
}
return tmp;
}
void add(){
string father,son;
while(cin>>father>>son){
if(find_index(?,father)==NULL){//I don't know what node to put instead of question mark and is my function working
size++;
Node *newnode=new Node();
newnode->key=father;
newnode->parent=NULL;
}
else if(find_index(t,son)==NULL){
size++;
Node *newnode1=new Node();
newnode1->key=son;
newnode1->parent->children.push_back(newnode1);
}
else{
Node *newnode2=new Node();
newnode2->key=father;
Node *newnode3=new Node();
newnode3->key=son;
newnode2->children.push_back(newnode3);
newnode3->parent=newnode2;
}
}
}
};
我怀疑您的代码是否有效。我可以看到以下问题:
find_index
:如果 cur 为 NULL,则您在 cur->key
(第一个 if
) 上出现段错误
find_index
: 你从不评估 foor 循环中的结果
add
:您需要为 ?
部分存储树的根。
我不知道,您输入的实际情况如何。如果我们知道输入将自上而下地描述一棵树,我们可以存储单个根。不过,我将在 add
期间存储多个根。这样,您也可以自下而上地构建树。
可能的解决方案是 something like this。
我正在尝试实现一棵树,该树在给定节点处存储子向量。我已经实现了查找节点的 find_index
函数。它有两个参数:Node * cur
和一些 key
。我在处理 insert
时尝试使用此功能,但我不知道要搜索什么 Node*
。这样的节点肯定是存在的,但是不知道用哪个来调用find_index
。我也不知道我的功能是否正常工作。提前致谢。
#include <iostream>
#include <vector>
using namespace std;
class Node{
public:
Node *parent;
vector < Node* > children;
string key;
Node(){
parent=NULL;
}
};
class tree{
public:
int size;
tree(){
size=0;
}
Node* find_index(Node *cur,string key){
Node *tmp;
if(cur->key==key){
tmp=cur;
}
if(cur==NULL){
tmp=NULL;
}
for(int i=0;i<cur->children.size();i++){
find_index(cur->children[i],key);
}
return tmp;
}
void add(){
string father,son;
while(cin>>father>>son){
if(find_index(?,father)==NULL){//I don't know what node to put instead of question mark and is my function working
size++;
Node *newnode=new Node();
newnode->key=father;
newnode->parent=NULL;
}
else if(find_index(t,son)==NULL){
size++;
Node *newnode1=new Node();
newnode1->key=son;
newnode1->parent->children.push_back(newnode1);
}
else{
Node *newnode2=new Node();
newnode2->key=father;
Node *newnode3=new Node();
newnode3->key=son;
newnode2->children.push_back(newnode3);
newnode3->parent=newnode2;
}
}
}
};
我怀疑您的代码是否有效。我可以看到以下问题:
find_index
:如果 cur 为 NULL,则您在cur->key
(第一个if
) 上出现段错误
find_index
: 你从不评估 foor 循环中的结果add
:您需要为?
部分存储树的根。
我不知道,您输入的实际情况如何。如果我们知道输入将自上而下地描述一棵树,我们可以存储单个根。不过,我将在 add
期间存储多个根。这样,您也可以自下而上地构建树。
可能的解决方案是 something like this。