【二叉树】基本操作集

//ABC##DE#G##F### 
#include <iostream>
#include <cstring>
using namespace std;

typedef struct node
{
	char data;
	struct node *lchild;
	struct node *rchild;
}BTnode;

char a[100];
int cur = -1;

//建树(先序)
void Create(BTnode *&T)
{
	cur++; 
	if(cur >= strlen(a)) return;
	if(a[cur] == '#')
	{
		T = NULL;
	}
	else
	{
		T = new BTnode;
		T->data = a[cur];
		Create(T->lchild);
		Create(T->rchild);
	}
} 

//先序遍历 
void Pre(BTnode *T)
{
	if(T)
	{
		cout<<T->data<<" ";
		Pre(T->lchild);
		Pre(T->rchild);
	}
	
}

//中序遍历 
void Mid(BTnode *T)
{
	if(T == NULL) return;
	Mid(T->lchild);
	cout<<T->data;
	Mid(T->rchild);
} 

//后序遍历 
void Pos(BTnode *T)
{
	if(T == NULL) return;
	Pos(T->lchild);	
	Pos(T->rchild);
	cout<<T->data<<" ";
}

//层次遍历(bfs) 
void Level(BTnode *T)
{
	if(T == NULL) return;
	BTnode *a[100];
	int front = -1, rear = 0;
	a[0] = T;
	while(front != rear)
	{
		front++;
		cout<<a[front]->data;
		if(a[front]->lchild) a[++rear] = a[front]->lchild;
		if(a[front]->rchild) a[++rear] = a[front]->rchild;
	}
}

int GetHeight(BTnode *T)	//求树的高度(后序)当前高度等于左子树高度加右子树高度的最大值+1 
{
	if(T == NULL)
	return 0;
	
	return max(GetHeight(T->lchild), GetHeight(T->rchild)) + 1;
}

void Leaves(BTnode *T)		//输出叶子结点(后序)
{
	if(T == NULL) return;
	if(!T->lchild && !T->rchild) cout<<T->data<<" "; 
	else
	{
		Leaves(T->lchild);
		Leaves(T->rchild);
	}
}

int LeavesNum(BTnode *T)	//输出叶子结点个数(后序)
{
	if(T == NULL) return 0;
	if(!T->lchild && !T->rchild) return 1;
	return LeavesNum(T->lchild) + LeavesNum(T->rchild);
}

void Copy(BTnode *T, BTnode *&t)	//复制二叉树(先序)
{
	if(T == NULL)
	{
		t = NULL;
	}
	else
	{
		t = new BTnode;
		t->data = T->data;
		Copy(T->lchild, t->lchild);
		Copy(T->rchild, t->rchild);
	}
} 

int main()
{
	BTnode *T, *t;
	cin>>a; 
	Create(T);
	//Mid(T);
	Pre(T);
	cout<<endl;
	Copy(T, t);
	Level(t);
	cout<<endl;
	//Leaves(T);
	//cout<<LeavesNum(T)<<endl;
	//cout<<GetHeight(T)<<endl;
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值