自写简易二叉树的一些实现

#include<iostream>
using namespace std;
struct Node
{
	char data;
	Node *lc;
	Node *rc;
};
Node* create()
{
	Node* p=(Node*)malloc(sizeof(Node)),*temp;
	temp=p;
	char ch='a';
	temp->data=ch;
	temp->lc=(Node*)malloc(sizeof(Node));
	temp->rc=(Node*)malloc(sizeof(Node));
	temp->lc->data=++ch;
	temp->rc->data=++ch;

	temp=p->lc;
	temp->lc=(Node*)malloc(sizeof(Node));
	temp->rc=(Node*)malloc(sizeof(Node));
	temp->lc->data=++ch;
	temp->rc->data=++ch;
	temp->lc->lc=NULL;
	temp->lc->rc=NULL;
	temp->rc->lc=NULL;
	temp->rc->rc=NULL;

	temp=p->rc;
	temp->lc=(Node*)malloc(sizeof(Node));
	temp->rc=(Node*)malloc(sizeof(Node));
	temp->lc->data=++ch;
	temp->rc->data=++ch;
	temp->lc->lc=NULL;
	temp->lc->rc=NULL;
	temp->rc->lc=NULL;
	temp->rc->rc=NULL;
	return p;
}
void xiangen(Node* head)//先根遍历
{
	if(head!=NULL)
	{
		cout<<head->data<<",";
		xiangen(head->lc);
		xiangen(head->rc);
	}
}
void zhonggen(Node* head)//中根遍历
{
	if(head!=NULL)
	{
		zhonggen(head->lc);
		cout<<head->data<<",";
		zhonggen(head->rc);
	}
}
void hougen(Node* head)//后根遍历
{
	if(head!=NULL)
	{
		hougen(head->lc);
		hougen(head->rc);
		cout<<head->data<<",";
	}
}
Node* find(Node* head,char x)
{
	if(head!=NULL)
	{
	if(head->data==x)
		return head;
	Node *temp=find(head->lc,x);
	if(temp!=NULL)
		return temp;
	else
		return find(head->rc,x);
	
	}
	return NULL;
}
int height(Node* head)
{
	int lc,rc;
	if(head==NULL) return 0;
	else
	{
		lc=height(head->lc);
		rc=height(head->rc);
		return (lc>rc)?(lc+1):(rc+1);
	}
}
int main()
{
	Node* p=create();
	Node* t;
	cout<<"先根遍历:"<<endl;
	xiangen(p);cout<<endl;
	cout<<"中根遍历:"<<endl;
	zhonggen(p);cout<<endl;
	cout<<"后根遍历:"<<endl;
	hougen(p);cout<<endl;
	t=find(p,'g');
	cout<<"查找到的数据:"<<t->data<<endl;
	cout<<"树高:"<<height(p)<<endl;
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值