//*************************************************************************************************************************************
//构造一棵二叉树,一个节点最多有两个儿子,但有可能有很多堂兄弟,这样对输入造成不便,从而选择先序构造树比较方便
typedef struct Tr
{
char ele;
Tr *left;
Tr *right;
Tr(char el,Tr * lchild=NULL,Tr * rchild =NULL )//构造函数,用来实现前序输入元素
{
ele=el;
left=lchild;
right=rchild;
}
~Tr(){cout<<"good";}
}Tr;
void createTr(Tr * &root)//按照前序输入节点
{
char ele;
cout<<"input the root if you donot want continue the nod input enough '2'"<<endl;
cin>>ele;//这里只是输入ele 而并不是root->ele
if('2'==ele)//将数字2作为一棵树的结束标志,同样注意这里只是单纯的ele ,还没有赋给节点
return;
else
{
root=new Tr(ele);//这里为嘛非要用new 呢?
createTr(root->left);
createTr(root->right);
}
}
void PrePut(Tr *root)
{
if (root == NULL)
return;
else
{
cout<<root->ele<<" ";
PrePut(root->left);
PrePut(root->right);
}
}
void backput(Tr *root)
{
if(root==NULL)
return;
else
{
backput(root->right);
backput(root->left);
cout<<root->ele<<" ";
}
}
int main()
{
Tr *root=NULL;
int n=0;
cout<<"input the tree from root in the way of preorder"<<endl;
createTr(root);
cout<<"choose the way to output"<<endl;
cout<<"1 Preorder"<<endl<<"2 BackOrder"<<endl;
cin>>n;
switch(n){
case 1:
cout<<"the Preorder is :\t";
PrePut(root);break;
case 2:
cout<<"The BackOrder is :\t";
backput(root);break;
default:
cout<<"choose 1 or 2"<<endl;
}
return 0;
}
构造二叉树并输出
最新推荐文章于 2024-01-11 20:55:59 发布