#include <stdio.h>
#include <stdlib.h>
#include <stack>
#include <queue>
using namespace std;
/*节点定义*/
typedef struct BTNode{
int tag;
int data;
struct BTNode *rchild;
struct BTNode *lchild;
}BiTNode;
/*创建二叉树*/
int CreatBiTree(BiTNode **T)
{
int ch;
scanf("%d",&ch);
if(ch==-1){
*T=NULL;
return 0;
}
else{
*T= new BiTNode;
if(T==NULL){printf("分配内存失败");return 0;}
(*T)->data=ch;
(*T)->tag=1;
printf("输入左结点");
CreatBiTree(&((*T)->lchild));
printf("输入有右结点");
CreatBiTree(&((*T)->rchild));
}
return 1;
}
/*前序遍历*/
int PreOrderBiTree(BiTNode *T)
{
if(T==NULL)return 0;
printf("%d",T->data);
PreOrderBiTree(T->lchild);
PreOrderBiTree(T->rchild);
return 1;
}
int PreOrderBiTree1(BiTNode *T)
{//非递归实现前序遍历
stack<BiTNode*> S;
do{
while(T!=NULL)
{
printf("%d",T->data);
S.push(T);
T=T->lchild;
}
if(!S.empty())
{
BiTNode *tempP;
tempP=S.top();
S.pop();
T=tempP->rchild;
}
}while(!S.empty()||T!=NULL);
}
/*中序遍历*/
int MiddleOrderBiTree(BiTNode *T)
{
if(T==NULL)return 0;
MiddleOrderBiTree(T->lchild);
printf("%d",T->data);
MiddleOrderBiTree(T->rchild);
}
int MiddleOrderBiTree1(BiTNode *T)
{//非递归实现前序遍历
stack<BiTNode*> S;
do{
while(T!=NULL)
{
S.push(T);
T=T->lchild;
}
if(!S.empty())
{
BiTNode *tempP;
tempP=S.top();
S.pop();
printf("%d",tempP->data);
T=tempP->rchild;
}
}while(!S.empty()||T!=NULL);
}
/*后序遍历*/
int PostOrderBiTree(BiTNode *T)
{
if(T==NULL)return 0;
PostOrderBiTree(T->lchild);
PostOrderBiTree(T->rchild);
printf("%d",T->data);
}
/*后序遍历的非递归实现*/
int PostOrderBiTree2(BiTNode *T)
{
stack<BiTNode*> S;
do{
while(T!=NULL)
{
S.push(T);
T=T->lchild;
}
if(!S.empty()&&(S.top())->tag==1)
{
(S.top())->tag=2;
T=S.top()->rchild;
}
else if(!S.empty()&&S.top()->tag==2)
{
BiTNode* d= S.top();
S.pop();
printf("%d",d->data);
}
}while(!S.empty()||T!=NULL);
}
/*层次序遍历*/
void LevelOrderBiTree(BiTNode *T)
{
queue<BiTNode*> So;
So.push(T);
BiTNode* ss = So.front();
while(ss!=NULL){
printf("%d", ss->data);
So.pop();
So.push(ss->lchild);
So.push(ss->rchild);
ss = So.front();
};
}
/*二叉树深度*/
int depth(BiTNode *T)
{
if(T==NULL)return 0;
int l=depth(T->lchild);
int r=depth(T->rchild);
if(l<=r)return r+1;
else return l+1;
}
/*二叉树复制*/
void CopyBTree(BiTNode* t,BiTNode* str)//将t赋值给str
{
if(t==NULL) str=NULL;
if(t!=NULL){
str=new BiTNode;
str->data=t->data;
CopyBTree(t->lchild,str->lchild);
CopyBTree(t->rchild,str->rchild);
}
}
int main()
{
BiTNode *p;
CreatBiTree(&p);
printf("前序遍历:\n");
PreOrderBiTree(p);
printf("\n中序遍历\n");
MiddleOrderBiTree(p);
printf("\n后序遍历\n");
PostOrderBiTree(p);
printf("\n层次序遍历\n");LevelOrderBiTree(p);
printf("\n树的深度\n");
printf("\n%d",depth(p));
BiTNode* cp;
CopyBTree(p,cp);
if(cp==NULL)printf("ll");
PostOrderBiTree(cp);
}
网友评论