创建二叉树
typedef struct BiTNode{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
void Create(BiTree &T)
{
char c;
cin>>c;
if(c=='#')
{
T= nullptr;
} else{
T=new BiTNode;
T->data=c;
Create(T->lchild);
Create(T->rchild);
}
}
先序中序后序遍历
void PreOrderTraverse(BiTree T)
{
if(T)
{
std::cout<<T->data; //AB#CD##E##F#GH###
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}
}
void InOrderTraverse(BiTree T)
{
if(T)
{
InOrderTraverse(T->lchild);
std::cout<<T->data;
InOrderTraverse(T->rchild);
}
}
void PostOrderTraverse(BiTree T)
{
if(T)
{
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
std::cout<<T->data;
}
}
层次遍历
线索二叉树
#include <iostream>
typedef struct ThreadNode{
int data;
struct ThreadNode *lchild,*rchild;
int ltag,rtag;
}ThreadNode,*ThreadTree;
ThreadNode *final= nullptr;
ThreadNode *pre= nullptr;
ThreadNode *p= nullptr;
void visit(ThreadNode *q)
{
if(p==q)
{
final=q;
}
else{
pre=q;
};
}
void InTraverseOrder(ThreadTree T)
{
if(T)
{
InTraverseOrder(T->lchild);
visit(T);
InTraverseOrder(T->rchild);
}
}