欢迎使用CSDN-markdown编辑器

一、二叉树的建立

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;
    }
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值