数据结构-----树(算法)

中序遍历的非递归算法

void InOrder(Bitree T)
{
	InitStack(S);p=T;
	q=new BiTNode;
	while(p||!StackEmpty(S))
	{
		if(p)
		{
			Push(S,p);
			p=p->lchild;
		}
		else
		{
			Pop(S,q);
			cout<<q->data;
			p=q->rchild;
		}
	}
}

复制二叉树

void Copy(Bitree T,Bitree &NewT)
{
	if(T==NULL)
	{
		NewT=NULL;
		return ;
	}
	else
	{
		NewT=new BitNode;
		NewT->data=T->data;
		Copy(T->lchild,NewT->lchild);
		Copy(T->rchild,NewT->rchild);
	}
}

计算二叉树的深度

int Depth(Bitree T)
{
	if(T==NULL)return 0;
	else
	{
		m=Depth(T->lchild);
		n=Depth(T->rchild);
		return (m>n?m:n)+1;
	}
}

计算二叉树中结点个数

int NodeCount(Bitree T)
{
	if(T==NULL) return 0;
	else return NodeCount(T->lchild)+NodeCount(T->rchild)+1;
	
}

统计二叉树的叶结点个数

int LeafNodeCount(Bitree T)
{
	if(T==NULL)
	return 0;
	else if(T->lchild==NULL&&T->rchild==NULL)
	return 1;
	else return LeafNodeCount(T->lchild)+LeafNodeCount(T->rchild);
}

判别两棵树是否相等

bool compTree(BTree a, BTree b)
{
	if(a == NULL && b == NULL)
		return true;
	if(a == NULL && b != NULL || a != NULL && b == NULL)
		return false;
	if(a->data == b->data)
	{
		if(compTree(a->lChild, b->lChild))
			return compTree(a->rChild, b->rChild))
		else if(compTree(a->lChild, b->rChild))
		return compTree(a->rChild, b->lChild);
	}
	return false;
}

交换二叉树每个结点左孩子和右孩子


void  ChangeLR(Bitree &T)
{
	Bitree temp;
	if(T->lchild==NULL&&T->rchild==NULL)
	return ;
	else 
	{
		temp=T->lchild;
		T->lchild=T->rchild;
		T->rchild=temp;
	}
	ChangeLR(T->lchild);
	ChangeLR(T->rchild);
}

双序遍历二叉树



void twoorder(Bitree T)
{
	if(T)
	{
		cout<<T->data;
		twoOrder(T->lchild);
		cout<<T->data;
		twoOrder(T->rchild);		
	}

}

计算二叉树的最大宽度

int width(Bitree T)
{
	if(T==NULL) return 0;
	else
	{
		Bitree Q[]; //Q 是队列,元素为二叉树结点指针
		forn=1;rear=1;last=1;
		//front 队头指针, rear队尾指针,last同层最右结点在队列中的位置
		temp=0;maxw=0; //temp记录局部宽度,maxw记录最大宽度
		Q[rear]=T;
		while(fornt<last)
		{
			p=Q[front++]; temp++;
			if(p->lchild!=NULL) Q[++rear] = p->lchild; //左子女入队
			if(p->rchild!=NULL) Q[++rear] = p->rchild; //右子女入队
			if(front>last)   //一层结束
			{
				//last 指向下层最右元素,更新当前最大宽度 
				last=rear;
				if(temp>maxw)maxw=temp;
				temp=0;	
			}	
		} 
		return maxw;
	}
}

统计树中度为1的结点数目

int Level(Bitree T)
{
	int num=0;
	if(T)
	{
		QueueInit(Q);QueueIn(Q,bt);
		while(!QueueEmpty(Q))
		{
			p=QueueOut(Q);//出队 
			//有左孩子没有右孩子,有右孩子没有左孩子 
			if((p->lchild&&!p->rchild)||(p->rchild&&!p->lchild))num++;
			if(p->lchild) QueueIn(Q,p->lchild);
			if(p->rchild) QueueIn(Q,p->rchild);
			
		}
	}
	return num;
 } 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值