数据结构备考——第五章二叉树

这篇博客介绍了二叉树的链式存储结构,包括如何通过先序遍历创建二叉树、复制二叉树、计算叶节点数量、判断两棵树是否相等、统计度为1的节点数量、求树的深度以及判断是否为正则二叉树。此外,还提供了层次遍历来统计度为1的节点,但该部分代码需要修复。
#include<bits/stdc++.h>
using namespace std;

//二叉树的链式存储结构    ok
typedef struct BNode{
	ElemType data;
	struct BNode *lchild,*rchild;
}BNode,*BTree;

//先序遍历的方式建立二叉链表   ok
char ch;
void CreateT(BTree &T){
	cin>>ch;
	if(ch=='#'){
		T=NULL;
	}
	else{
		T=new BNode;
		T->data=ch;
		CreateT(T->lchild);
		CreateT(T->rchild);
	}
}

//复制二叉树   ok
void Copy(BTree T,BTree &NewT){
	if(T==NULL){
		NewT=NULL;
		return;
	}
	else{
		NewT=new BTree;
		NewT->data=T->data;
		Copy(T->lchild,NewT->lchild);
		Copy(T->rchild,NewT->rchild);
	}
}
//二叉树中叶结点的个数   ok
int nodecount(BiTree T){
	if(T==NULL){
		return 0;
	}
	if(T->lchild==NULL&&T->rchild==NULL){
		return 1;
	}
	else return nodecount(T->lchild)+nodecount(T->rchild);
}

//二叉树中结点的个数
int nodecount(BiTree T){
	if(T==NULL){
		return 0;
	}
	else return 1+nodecount(T->lchild)+nodecount(T->rchild);
}

//判别两棵树是否相等   参数是BiNode * 类型 ok
bool issame(BiNode *T1,BiNode *T2){
	if(T1==NULL&&T2==NULL){
		return true;
	}
	if(T1==NULL||T2==NULL){
		return false;
	}
	if(T1->data!=T2->data){
		return false;
	}
	else{
		if(issame(T1->lchild,T2->lchild)&&issame(T1->rchild,T2->rchild)){
			return true;
		}
	}
}

//层次遍历二叉树,统计度为1的结点数目  改正了,首先要保证树不为空    参数是BiTree类型,不是BiNode *类型
//还需要再次修改****************
int nodecount(BiTree T){
	int num=0;
	if(T){
		BiTree p;
		SQueue Q;
		InitQ(Q);
		Queuein(Q,T);
		while(!EmptyQ(Q)){
			p=Queueout(Q);
			cout<<p->data;
			if(p->lchild!=NULL) Queuein(Q,p->lchild);
			if(p->rchild!=NULL) Queuein(Q,p->rchild);
			if((p->lchild==NULL&&p->rchild!=NULL)||(p->lchild!=NULL&&p->rchild==NULL)){
				num++;
			}
			
		}
	}

	return num;
}

//统计度为1的结点数目  ok
int nodecount(BiTree T){
	if(T==NULL){
		return 0;
	}
	else if((T->lchild==NULL&&T->rchild!=NULL)||(T->lchild!=NULL&&T->rchild==NULL)){
		return 1+nodecount(T->lchild)+nodecount(T->rchild);
	}
	else return nodecount(T->lchild)+nodecount(T->rchild);
}


//求二叉树的深度  ok
int depth(BiTree T){
	if(T==NULL){
		return 0;
	}
	else{
		int m,n;
		m=depth(T->lchild);
		n=depth(T->rchild);
		if(m>n){
			return 1+m;
		}
		else return 1+n;
	}
}

//求任意二叉树中第一条最长的路径长度,并输出此路径上各结点的值  参数应该是BiNode *类型  ok
void echopath(BiNode *T){
	if(T){
		printf("%d ",T->data);
		if(depth(T->lchild)>depth(T->rchild)){
			echopath(T->lchild);
		}
		else echopath(T->rchild);
	}
}

//判断是否是正则二叉树   ok
bool judge(BiTree T){
	if(T==NULL){
		return true;
	}
	else if(T->lchild==NULL&&T->rchild==NULL){
		return true;
	}
	else if(T->lchild!=NULL&&T->rchild!=NULL){
		if(judge(T->lchild)&&judge(T->rchild)){
			return true;
		}
		else return false;
	}
	else return false;
}

int main(){
	
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值