名词
完全二叉树:只有最后一层不满,其余节点都有两个孩子,并且最后一层的节点从左向右排列,如下图
扩充二叉树:每个实节点都有两个孩子,如图
类型定义
typedef char DataType;
typedef struct BTreeNode
{
DataType data;
struct BTreeNode * leftchild;
struct BTreeNode * rightchild;
}BinTreeNode;
typedef BinTreeNode * BinTree;
先序遍历
void PreOrder_Recursion(BinTree bt)//类似DFS
{
if(bt==NULL)
{
return;
}
cout<<bt->data<<" ";
PreOrder_Recursion(bt->leftchild);
PreOrder_Recursion(bt->rightchild);
}
中序遍历
void InOrder_Recursion(BinTree bt)
{
if(bt==NULL)
{
return;
}
InOrder_Recursion(bt->leftchild);
cout<<bt->data<<" ";
InOrder_Recursion(bt->rightchild);
}
后序遍历
void PostOrder_Recursion(BinTree bt)
{
if(bt==NULL)
{
return;
}
PostOrder_Recursion(bt->leftchild);
PostOrder_Recursion(bt->rightchild);
cout<<bt->data<<" ";
}
层序遍历
void LevelOrder(BinTree bt)//类似BFS
{
BinTree p;
queue<BinTree> q;
if(bt==NULL)
{
return;
}
p=bt;
q.push(bt);
while(!q.empty())
{
p=q.front();
q.pop();
cout<<p->data<<" ";
if(p->leftchild!=NULL)
{
q.push(p->leftchild);
}
if(p->rightchild!=NULL)
{
q.push(p->rightchild);
}
}
}
建树
BinTree CreateBinTree_Recursion()//输入对应扩展二叉树的先序
{
char ch;
BinTree bt;
cin>>ch;
if(ch=='@')
{
bt=NULL;
}
else
{
bt=(BinTreeNode *)malloc(sizeof(BinTreeNode));
bt->data=ch;
bt->leftchild=CreateBinTree_Recursion();
bt->rightchild=CreateBinTree_Recursion();
}
return bt;
}
完整
#include <bits/stdc++.h>
using namespace std;
typedef char DataType;
typedef struct BTreeNode
{
DataType data;
struct BTreeNode * leftchild;
struct BTreeNode * rightchild;
}BinTreeNode;
typedef BinTreeNode * BinTree;
void PreOrder_Recursion(BinTree bt)
{
if(bt==NULL)
{
return;
}
cout<<bt->data<<" ";
PreOrder_Recursion(bt->leftchild);
PreOrder_Recursion(bt->rightchild);
}
void InOrder_Recursion(BinTree bt)
{
if(bt==NULL)
{
return;
}
InOrder_Recursion(bt->leftchild);
cout<<bt->data<<" ";
InOrder_Recursion(bt->rightchild);
}
void PostOrder_Recursion(BinTree bt)
{
if(bt==NULL)
{
return;
}
PostOrder_Recursion(bt->leftchild);
PostOrder_Recursion(bt->rightchild);
cout<<bt->data<<" ";
}
void LevelOrder(BinTree bt)
{
BinTree p;
queue<BinTree> q;
if(bt==NULL)
{
return;
}
p=bt;
q.push(bt);
while(!q.empty())
{
p=q.front();
q.pop();
cout<<p->data<<" ";
if(p->leftchild!=NULL)
{
q.push(p->leftchild);
}
if(p->rightchild!=NULL)
{
q.push(p->rightchild);
}
}
}
BinTree CreateBinTree_Recursion()
{
char ch;
BinTree bt;
cin>>ch;
if(ch=='@')
{
bt=NULL;
}
else
{
bt=(BinTreeNode *)malloc(sizeof(BinTreeNode));
bt->data=ch;
bt->leftchild=CreateBinTree_Recursion();
bt->rightchild=CreateBinTree_Recursion();
}
return bt;
}
int main()
{
BinTree root=CreateBinTree_Recursion();
PreOrder_Recursion(root);
cout<<endl;
InOrder_Recursion(root);
cout<<endl;
PostOrder_Recursion(root);
cout<<endl;
LevelOrder(root);
}