这个数据结构有讲到,如果一点都不懂可以看看数据结构的树那一章
代码如下,思路见代码
#include<bits/stdc++.h>
using namespace std;
struct mTreeNode{
mTreeNode():val(0){}
int val;
vector<mTreeNode * > son;
};
struct treeNode{
treeNode():val(0),bro(nullptr),son(nullptr){}
int val;
treeNode * son;
treeNode * bro;
};
treeNode * func(mTreeNode * mRoot,mTreeNode * pRoot,int index){
if(!mRoot)
return nullptr;
treeNode * temp = new treeNode();
temp->val = mRoot->val;
auto sonArr = mRoot->son;
int sz = sonArr.size();
if(sz)
{
temp->son = func(sonArr[0],mRoot,1);
}
if(pRoot)
{
temp->bro = (index + 1 > pRoot->son.size() ? nullptr : func(pRoot->son[index],pRoot,index + 1));
}
return temp;
}
void checkTreeNode(treeNode * root){
queue<treeNode * > q,p,p1;
q.push(root);
while(q.size()){
treeNode * temp = q.front(); q.pop();
cout << temp->val << '\t';
if(temp->son)
p.push(temp->son);
if(temp->bro)
p.push(temp->bro);
if(!q.size())
{
q = p;
p = p1;
cout << '\n';
}
}
}
void checkmTree(mTreeNode * root){
queue<mTreeNode * > q,p,p1;
q.push(root);
while(q.size()){
mTreeNode * temp = q.front(); q.pop();
cout << temp->val << '\t';
for(auto it : temp->son)
{
p.push(it);
}
if(!q.size())
{
q = p;
p = p1;
cout << '\n';
}
}
}
mTreeNode * createmNode(int n,int m){
if(!n)
return nullptr;
mTreeNode * root = new mTreeNode();
root->val = rand() % 50;
if(n > 1)
for(int i = 1; i <= m; ++i){
mTreeNode * temp = createmNode(n - 1,m);
root->son.push_back(temp);
}
return root;
}
int main(){
int n,m; cin >> n >> m;
mTreeNode * mRoot = createmNode(n,m);
checkmTree(mRoot);
treeNode * root = func(mRoot,nullptr,0);
checkTreeNode(root);
return 0;
}
|