最近在写一个决策树的程序,苦于每个节点的孩子数目不确定建树困难,通过查询资料发现可以通过容器来写很方便。
首先结构体代码如下:
typedef struct Node{ string Data; //数据存储项,用于保存相应的数据 vector<Node*> Children; //孩子节点指针存储,用于存储指向孩子节点的指针 }Node;
然后是建立三叉树的建树代码:
void BuildTree(Node *root) { string str; cin>>str; cout<<str<<endl; if(str=="END") { cout<<"leave"<<endl; Node *t=new Node; t->Data="END"; root->Children.push_back(t); return; } else { cout<<"brand"<<endl; Node *t=new Node; t->Data=str; root->Children.push_back(t); for(int i=0;i<3;i++) BuildTree(t); } }
接着是遍历三叉树的遍历函数:
void Show(Node *root) { if(root->Data=="END") { cout<<"Leave node"<<endl; return; } else { cout<<root->Data<<endl; for(vector<Node*>::iterator it=root->Children.begin();it!=root->Children.end();it++) { Node* temp=*it; Show(temp); } } }
最后是主调用函数:
int main() { Node *root; root=new Node; BuildTree(root); Show(root); return 0; }
输出结果: