欢迎使用CSDN-markdown编辑器

来源:互联网 发布:物流软件定制开发 编辑:程序博客网 时间:2024/06/06 01:35

一、二叉树的建立

1、建立结构体
typedef char ElemType;
typedef struct BtNode //结构体
{
BtNode *leftchild;
BtNode *rightchild;
ElemType data;
}BtNode, *BinaryTree;
2、购买结点
BtNode * Buynode()
{
BtNode s = (BtNode)malloc(sizeof(BtNode));
if(s == NULL) exit(1);
memset(s,0,sizeof(BtNode));//清零
return s;
}
3、建立二叉树
通过递归调用实现
BtNode * CreateTree()
{
BtNode *s = NULL;
ElemType item;
scanf(“%c”,&item);
if(item != ‘#’)
{
s = Buynode();
s->data = item;
s->leftchild = CreateTree();
s->rightchild = CreateTree();
}
return s;
}
4、前、中、后遍历的实现
①前序遍历
void PreOrder(BtNode *ptr)
{
if(ptr != NULL)
{
printf(“%c “,ptr->data);
PreOrder(ptr->leftchild);
PreOrder(ptr->rightchild);
}
}
②中序遍历
void InOrder(BtNode *ptr)
{
if(ptr != NULL)
{
InOrder(ptr->leftchild);
printf(“%c “,ptr->data);
InOrder(ptr->rightchild);
}
}
③后序遍历
void PastOrder(BtNode *ptr)
{
if(ptr != NULL)
{
PastOrder(ptr->leftchild);
PastOrder(ptr->rightchild);
printf(“%c “,ptr->data);
}
}
④非递归前序遍历
void NicePerOrder(BtNode *ptr)
{
if(ptr == NULL) return ;
Stack st;
Init_Stack(&st);
push(&st,ptr);
while(!empty(&st))
{
ptr = top(&st);//得到栈顶元素
pop(&st);//出栈
printf(“%c “,ptr->data);
if(ptr->rightchild != NULL)
push(&st,ptr->rightchild);//进栈
if(ptr->leftchild != NULL)
push(&st,ptr->leftchild);
}
}
⑤非递归中序遍历
void NiceInOrder(BtNode *ptr)
{
if(ptr == NULL) return ;
Stack st; // BtNode *;
Init_Stack(&st);

while(ptr != NULL || !empty(&st)){    while(ptr != NULL)    {        push(&st,ptr);        ptr = ptr->leftchild;    }    ptr = top(&st); pop(&st);    printf("%c ",ptr->data);    ptr = ptr->rightchild;}

}
⑥非递归后序遍历
void NicePastOrder(BtNode *ptr)
{
if(ptr == NULL) return ;
Stack st; // BtNode *;
Init_Stack(&st);
BtNode *tag = NULL;

while(ptr != NULL || !empty(&st)){    while(ptr != NULL)    {        push(&st,ptr);        ptr = ptr->leftchild;    }    ptr = top(&st); pop(&st);    if(ptr->rightchild == NULL || ptr->rightchild == tag)    {        printf("%c ",ptr->data);        tag = ptr;        ptr = NULL;    }    else    {        push(&st,ptr);        ptr = ptr->rightchild;    }}

}

原创粉丝点击