# include<stdio.h>
# include<malloc.h>
const int MAXSIZE=2000;
typedef struct node{
int data;
struct node * left, * right;
} BTree;
typedef struct stackelem{
BTree * a[MAXSIZE];
int top;
} Stack;
typedef struct queueelem{
BTree * b[MAXSIZE];
int front, rear;
} Queue;
//递归创建
BTree * Create(){
int data;
scanf("%d", &data);
if(data==0)
{
return NULL;
}
BTree * p= (BTree *)malloc(sizeof(BTree));
if(NULL==p) return NULL;
p->data=data;
p->left=Create();
p->right=Create();
return p;
}
void Preorder(BTree * bt)
{
if(NULL!=bt)
{
printf("%d ", bt->data);
Preorder(bt->left);
Preorder(bt->right);
}
}
void Preorder2(BTree* bt){
BTree *p;
Stack st;
st.top=-1;
if(NULL==bt)
{
return;
}
else
{
st.top++;
st.a[st.top]=bt;
while(st.top!=-1)
{
p=st.a[st.top];
st.top--;
printf("%d ", p->data);
if(p->right!=NULL)
{
st.top++;
st.a[st.top]=p->right;
}
if(p->left!=NULL)
{
st.top++;
st.a[st.top]=p->left;
}
}
}
}
void Inorder(BTree* bt)
{
if(NULL!=bt)
{
Inorder(bt->left);
printf("%d ", bt->data);
Inorder(bt->right);
}
}
void Inorder2(BTree * bt)
{
BTree *p, *q;
Stack st;
st.top=-1;
if(NULL==bt)
{
return;
}
else
{
while(bt!=NULL)
{
st.top++;
st.a[st.top]=bt;
bt=bt->left;
}
while(st.top!=-1)
{
p=st.a[st.top];
st.top--;
printf("%d ", p->data);
while(p->right!=NULL)
{
st.top++;
st.a[st.top]=p->right;
q=p->right;
while(q->left!=NULL)
{
st.top++;
st.a[st.top]=q->left;
q=q->left;
}
break;
}
}
}
}
void Postorder(BTree * bt)
{
if(bt!=NULL)
{
Postorder(bt->left);
Postorder(bt->right);
printf("%d ", bt->data);
}
}
void Postorder2(BTree *bt)
{
Stack st;
st.top=-1;
BTree* t;
int flag;
do{
while(bt!=NULL)
{
st.top++;
st.a[st.top]=bt;
bt=bt->left;
}
t=NULL;
flag=1;
while(st.top!=-1 && flag)
{
if(bt->right==t)
{
printf("%d ", bt->data);
st.top--;
t=bt;
}
else
{
bt=bt->right;
flag=0;
}
}
}while(st.top!=-1);
}
int Height(BTree *bt)
{
int depth1, depth2;
if(NULL==bt)
{
return 0;
}
else
{
depth1=Height(bt->left);
depth2=Height(bt->right);
return depth1>depth2?depth1+1:depth2+1;
}
}
void TraversalOfLevel(BTree *bt)
{
Queue q;
q.front=q.rear=0;
if(bt!=NULL)
{
printf("%d ", bt->data);
}
q.b[q.front]=bt;
q.rear=q.rear+1;
while(q.front<q.rear)
{
bt=q.b[q.front];
q.front++;
if(bt->left!=NULL)
{
printf("%d ", bt->left->data);
q.b[q.rear]=bt->left;
q.rear++;
}
if(bt->right!=NULL)
{
printf("%d ", bt->right->data);
q.b[q.rear]=bt->right;
q.rear++;
}
}
}
int main(void)
{
return 0;
}
二叉树
最新推荐文章于 2022-03-12 20:36:06 发布