递归之二叉树的建立和遍历

先序遍历建立二叉树:

/*
二叉树先序遍历,存放数据,打印出层数
左子树,右子树
*/
#include  <stdio.h>
#include  <iostream>
#include  <malloc.h>
using namespace std;
typedef  char   type;
typedef  struct node 
{
	type data;
	struct node *left_tree;
	struct node *rig_tree;
}tree,*tyust;
void  creat_tree(tyust &T)//创建一棵树
{
	char temp;
	scanf("%c",&temp);
	T=(tyust)malloc(sizeof(node));//为T分配一个地址
	if(' '==temp)//如果是空的
	{
		T=NULL;
	}else
	{
		T->data=temp;
		creat_tree(T->left_tree);//建立左子树
		creat_tree(T->rig_tree);//建立右子树
	}
}
void  search(tyust T,int level)
{
	if(T)//非空
	{
		cout<<T->data<<"在"<<level<<"层"<<endl;
		search(T->left_tree,level+1);//先序遍历左子树
		search(T->rig_tree,level+1);//先序遍历右子树
	}

}
void main()
{
	int level=1;
	tyust  bit_tree;
	
	creat_tree(bit_tree);
	search(bit_tree,level);
}

猜你喜欢

转载自blog.csdn.net/shuiyihang0981/article/details/82431242