二叉树例子

#include<iostream>
#include<bits/stdc++.h>
using namespace std;
typedef char TElemType;
typedef struct TreeNode
{
    TElemType data;
    struct TreeNode *left;
    struct TreeNode *right;
}Treenode;
typedef struct SNode
{
    int no;
    Treenode *node;
}StackNode;
int n,min1;
Treenode* buildTree()
{
    char x;
    scanf("%c",&x);
    if(x=='#')
    {
        return  NULL;
    }
    else
    {
        Treenode*p=(Treenode*)malloc(sizeof(Treenode));
        p->data=x;
        p->left=buildTree();
        p->right=buildTree();
        return p;
    }
};
//链式前序遍历
int  pre( Treenode *p)
{
    printf("%c ",p->data);
    if(p->left!=NULL)
   pre(p->left);
    if(p->right!=NULL)
    pre(p->right);
    return 0;
}
//链式中序遍历
int  in( Treenode *p)
{

    if(p->left!=NULL)
    in(p->left);
    printf("%c ",p->data);
    if(p->right!=NULL)
     in(p->right);
    return 0;
}
//链式后序遍历
int aft( Treenode *p)
{

    if(p->left!=NULL)
    aft(p->left);
    if(p->right!=NULL)
    aft(p->right);
    printf("%c ",p->data);
    return 0;
}
//非递归前序遍历
int pre1(Treenode *p)
{
    stack<Treenode*> s;
    while(!s.empty()||p)
    {
        if(p)
        {
            printf("%c ",p->data);
            s.push(p);
            p=p->left;
        }
        else
        {
            p=s.top();
            s.pop();
            p=p->right;
        }
    }
}
//非递归中序遍历
int in1(Treenode *p)
{
    stack<Treenode*> s;
    while(!s.empty()||p)
    {
        if(p)
        {
            s.push(p);
            p=p->left;
        }
        else
        {
            p=s.top();
            printf("%c ",p->data);
            s.pop();
            p=p->right;
        }
    }
}
//非递归后序遍历
int aft1(Treenode *p)
{
    stack<StackNode> s;
    while(!s.empty()||p)
    {
        if(p)
        {
            StackNode t;
            t.no=1;
            t.node=p;
            s.push(t);
            p=p->left;
        }
        else
        {
            StackNode t=s.top();
            if(t.no==1)
            {
                p=t.node->right;
                t.no=2;
                s.pop();
                s.push(t);
            }
           else
            {
                t=s.top();
                s.pop();
                printf("%c ",t.node->data);
            }
        }
    }
}

int main()
{
    int x,y;
    Treenode *h;
    h=buildTree();
    printf("先序遍历:");
     pre(h);
    printf("\n");
    printf("中序遍历:");
    in(h);
    printf("\n");
    printf("后序遍历:");
    aft(h);

     //非递归操作
    printf("\n\n非递归:");
    printf("\n非递归先序遍历:");
    pre1(h);
    printf("\n非递归中序遍历:");
    in1(h);
    printf("\n非递归后序遍历:");
    aft1(h);
    return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值