整理了下二叉树模板(持续更新中,以后碰到新的函数会慢慢补充)接下来就是代码,每个函数都有备注,也欢迎大家不断补充,一起完善。
代码:
#include <iostream>
#include <queue>
using namespace std;
struct Tree
{
int data;//数据域
Tree *lchild ,*rchild;//分别为左孩子有孩子
};
Tree *buildTree(Tree *bt)
{
int x;
cin>>x;
if(x==0) bt=NULL;//建立树的时候如果碰到0就代表空的节点 ,根据题意
else{
bt=new Tree;//分配空间
bt->data=x;
bt->lchild=buildTree(bt->lchild);
bt->rchild=buildTree(bt->rchild);
}
return bt;
}
void bianli(Tree *bt)//前序遍历,中序以及后续
{
if(bt==NULL) return;
else{
cout<<bt->data;
bianli(bt->lchild);
bianli(bt->rchild);
}
/*
中序遍历: bianli(bt->lchild);cout<<bt->data;bianli(bt->rchild);
后序遍历: bianli(bt->lchild);bianli(bt->rchild);cout<<bt->data;
*/
}
void cengxv(Tree *bt)
{
queue<Tree*>Q;//定义一个队列
Tree *temp;//定义一个新的结点
if(bt==NULL) return ;
Q.push(bt);
while(!Q.empty()){
temp=Q.front(); Q.pop();
cout<<temp->data<<" ";
if(temp->lchild!=NULL) Q.push(temp->lchild);
if(temp->rchild!=NULL) Q.push(temp->rchild);
}
}
int deepth(Tree *bt)//计算二叉树的深度
{
if(bt==NULL) return 0;
else
return max(deepth(bt->lchild),deepth(bt->rchild))+1;//画图模拟一遍
}
int main()
{
Tree *root;//树的根,还未分配空间,只是声明;
root=buildTree(root);//建树时需要将根节点的值传出来。
bianli(root);//前序中序后序遍历输出
cengxv(root);//层序遍历输出
deepth(root);//计算二叉树深度
}