构造二叉树并输出

//*************************************************************************************************************************************
//构造一棵二叉树,一个节点最多有两个儿子,但有可能有很多堂兄弟,这样对输入造成不便,从而选择先序构造树比较方便
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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值