二叉树遍历的应用

建立二叉链表存储结构,创建二叉树,求二叉树的叶子节点数,求二叉树的高度,翻转二叉树。

输入序列:1 2 0 4 0 0 3 5 0 0 0

#include<malloc.h>
#include<iostream>
#include<stdio.h>
#define TRUE 1
#define FALSE 0
#define ok 1
#define maxsize 100
using namespace std;
typedef struct binode
{
	int data;
	struct binode *lchild,*rchild;
}binode,*bitree;
int treecreated=FALSE;
int leafcount=0;
int creatbitree(bitree *T);
int preordertraverse(bitree T);
int height(bitree T);
void swap(bitree *T);
void Leafcount(bitree T);
void main()
{
	int choice=0;
	int leave=FALSE,flag;
	binode *BT;
	cout<<"======二叉树演示程序======="<<endl;
	do
	{
		cout<<"1.创建一个二叉树,按先序遍历结果输入,空用0表示"<<endl;
		cout<<"2.线序遍历二叉树,递归方式遍历二叉树"<<endl;
		cout<<"3.求叶子树"<<endl;
		cout<<"4.计算二叉树的高度"<<endl;
		cout<<"0.quit"<<endl;
		cout<<"----input your selection"<<endl;
		cin>>choice;
		switch(choice)
		{
		case 1:
			if(treecreated)
			{
				cout<<"sorry,the tree has been already created!"<<endl;
				break;
			}
			cout<<"put in numbers!"<<endl;
			flag=creatbitree(&BT);
			if(flag==ok)
			{
				cout<<"okey,the tree named BT is created.."<<endl;
				treecreated=TRUE;
			}
			break;
		case 2:
			if(!treecreated)
			{
				cout<<"you need creat a tree for further steps!"<<endl;
				break;
			}
			cout<<"pre order:";
			preordertraverse(BT);
				cout<<endl;
			break;
		case 3:
			if(!treecreated)
			{
				cout<<"you need creat a tree for further steps"<<endl;
				break;
			}
			Leafcount(BT);
			cout<<"leaf count is"<<leafcount<<endl;
			break;
		case 4:
			int h;
			h=height(BT);
			cout<<"the height is"<<h<<endl;
			break;
		case 5:
			swap(&BT);
			cout<<"okey,tree was swaped"<<endl;
			break;
		case 0:
			leave=TRUE;
			break;
		}
	}while(!leave);
	cout<<"thanks for using ,bye~"<<endl;
}
int creatbitree(bitree *T)
{
	int ch=0;
	cin>>ch;
	if(ch==0)
		(*T)=NULL;
	else
	{
		(*T)=(bitree)malloc(sizeof(binode));
		(*T)->data=ch;
		creatbitree(&(*T)->lchild);
		creatbitree(&(*T)->rchild);
	}
	return ok;
}
int preordertraverse(bitree T)
{
	if(T)
	{
		cout<<T->data<<"   ";
		preordertraverse(T->lchild);
		preordertraverse(T->rchild);
		return ok;
	}
	else
	return ok;
}
int height(bitree T)
{
	int hl,hr;
	if(T==NULL)
		return 0;
	hl=height(T->lchild)+1;
	hr=height(T->rchild)+1;
	return(hl>hr?hl:hr);
}
void swap(bitree *T)
{
	bitree p;
	if(*T!=NULL)
	{
		p=(*T)->lchild;
		(*T)->lchild=(*T)->rchild;
		(*T)->rchild=p;
		swap(&(*T)->lchild);
		swap(&(*T)->rchild);
	}
}
void Leafcount(bitree T)
{
	if(T)
	{
		leafcount++;
	if(T->lchild!=NULL)
	Leafcount(T->lchild);
	if(T->rchild!=NULL)
	Leafcount(T->rchild);
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值