树的四种遍历及求深度

在这里插入图片描述

/*
先序创建,空为999 
1 2 4 999 999 5 999 999 3 6 999 999 999
*/
#include<bits/stdc++.h>
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
typedef int ElemType;
typedef struct BiTNode{
	ElemType data;
	struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;

void InitTree(BiTree &root){
	root=(BiTree)malloc(sizeof(BiTNode));
	root->lchild=NULL;
	root->rchild=NULL;
}
BiTree CreatTree(BiTree t){//先序创建二叉树 
	ElemType x;	
	cin>>x;
	if(x==999) return NULL;
	else{
		t=(BiTree)malloc(sizeof(BiTNode));
		t->data=x;
		t->lchild=CreatTree(t->lchild);
		t->rchild=CreatTree(t->rchild);
	}
	return t;
}
void visit(BiTree t){
	printf("%d",t->data);
}
void PreOrder(BiTree T){//先序遍历 
	if(T!=NULL){
		visit(T);             //访问根结点 
		PreOrder(T->lchild);  //递归遍历左子树 
		PreOrder(T->rchild);  //递归遍历右子树 
	}
}
void InOrder(BiTree T){//中序遍历 
	if(T!=NULL){
		InOrder(T->lchild);  //递归遍历左子树 
		visit(T);             //访问根结点 
		InOrder(T->rchild);  //递归遍历右子树 
	}
}
void PostOrder(BiTree T){//后序遍历 
	if(T!=NULL){	
		PostOrder(T->lchild);  //递归遍历左子树 
		PostOrder(T->rchild);  //递归遍历右子树 
		visit(T);             //访问根结点 
	}
}
void LevelOrder(BiTree t){
	BiTNode *h;
	queue<BiTree>q;
	q.push(t);
	while(!q.empty()){
		h=q.front();
		q.pop();
		printf("%d",h->data);
		if(h->lchild!=NULL){	
			q.push(h->lchild);
		}
		if(h->rchild!=NULL){
			q.push(h->rchild);
		}
	}
	
}
int treeDepth(BiTree T){
	if(T==NULL) return 0;
	else {
		int l=treeDepth(T->lchild);
		int r=treeDepth(T->rchild);
		return l>r?l+1:r+1; 
	}
}
int main(){
	BiTree t;
	InitTree(t);
	t=CreatTree(t);
	cout<<"先序遍历:"; PreOrder(t);
	cout<<endl<<"中序遍历:"; InOrder(t);
	cout<<endl<<"后序遍历:"; PostOrder(t);
	cout<<endl<<"层序遍历:"; LevelOrder(t);
	cout<<endl<<"树的深度是"<<treeDepth(t);
	return 0;
} 

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清木!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值