1.声明及建立
typedef struct BiTNode{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
int node,leafnode,depth;
void CreateBiTree(BiTree &T)//先序建立二叉树
{
char ch;
scanf("%c",&ch);
if(ch=='#') T=NULL;
else
{
if(!(T=(BiTNode *)malloc(sizeof(BiTNode)))) exit(-1);
T->data=ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}2.遍历
A 中序遍历
1)递归方法(先序、后序改变一下VistElem()函数的位置即可)
int InOrderTraverse(BiTree T)//
{
if(T)
{
if(InOrderTraverse(T->lchild))//先遍历左子树
if(VistElem(T->data))//访问根结点
if(InOrderTraverse(T->rchild)) return 1;//再遍历右子树
return -1;
}
return 1;
}2)非递归实现
int InOrderFRE(BiTree T)//中序非递归1
{
stack<BiTree>s1;
BiTree t;
s1.push(T);
while(!s1.empty())
{
t=s1.top();
while(t)
{t=t->lchild;s1.push(t);}
s1.pop();//空指针退栈
if(!s1.empty())
{
t=s1.top();
s1.pop();
if(!VistElem(t->data)) return -1;
s1.push(t->rchild);
}
}
return 1;
}
int InOrderFRE2(BiTree T)//中序非递归2
{
stack<BiTree>s2;
BiTree p=T;
while(p||!s2.empty())
{
if(p) {s2.push(p);p=p->lchild;}
else
{
p=s2.top();
s2.pop();//根指针退栈
if(!VistElem(p->data)) return -1;
p=p->rchild;
}
}
return 1;
}注意两种非递归方法的不同
3)层序遍历
int LevelOrderTraverse(BiTree T)//层序遍历
{
queue<BiTree>q1;
if(T)
{
q1.push(T);
while(!q1.empty())
{
BiTree t=q1.front();
q1.pop();
VistElem(t->data);
if(t->lchild) q1.push(t->lchild);
if(t->rchild) q1.push(t->rchild);
}
}
return 1;
}
3.求深度
int Depth(BiTree T)
{
int ldepth,rdepth;
if(T)
{
ldepth=Depth(T->lchild);
rdepth=Depth(T->rchild);
}
else return 0;//空树返回0
return ldepth>rdepth?ldepth+1:rdepth+1;
}
本文详细介绍了二叉树的基本操作,包括二叉树的声明与建立、遍历方法(先序、中序、后序及层序遍历)、求深度等,并提供了递归与非递归实现方式。
9896

被折叠的 条评论
为什么被折叠?



