急求构建普通树(非二叉树)以及遍历的C⼀C++程序,先谢谢各位了!!!

2025-02-27 20:38:54
推荐回答(1个)
回答1:

#include "stdafx.h"
#include

using namespace std;

class tree
{
private:
int data;
vector childern;
public:
tree(int); //构造树的节点
void PlusChild(tree *); //向当前树增加叶子节点
int GetData(); //取得当前树的数据
void Enum(); //遍历当前树
};
tree::tree(int _data)
{
this->data = _data;
}
int tree::GetData()
{
return this->data;
}
void tree::Enum()
{
unsigned int size = this->childern.size();
printf("%d ", this->data);
for (unsigned int i = 0 ; i < size; i++ )
this->childern[i]->Enum();
}
void tree::PlusChild(tree * child )
{
this->childern.push_back( child );
}

int main(int argc, char* argv[])
{
tree t1(1);
tree t2(2);
tree t3(3);
tree t4(4);
tree t5(5);

t1.PlusChild(&t2);
t1.PlusChild(&t3);
t2.PlusChild(&t4);
t2.PlusChild(&t5);

t1.Enum();

getchar();
return 0;
}