二叉树的非递归遍历

复制代码
//非递归操作

#include <stdio.h>
#include <stdlib.h>

#define MaxSize 200 

typedef struct TreeNode{
    int data;
    struct TreeNode *lchild,*rchild;
}TreeNode,*Tree;

typedef struct{
    TreeNode* data[MaxSize];
    int top;
}Stack;

void InitStack(Stack &S)
{
    S.top=-1;
}

bool isEmpty(Stack S)
{
    if(S.top==-1)
        return true;
    return false;
}

int Push(Stack &S,TreeNode *p)
{
    if(S.top==MaxSize-1)
        return -1;
    S.data[++S.top]=p;
    return 0;
}

int Pop(Stack &S,TreeNode* &p)
{
    if(S.top==-1)
        return -1;
    p=S.data[S.top--];
    return 0;
}

int GetTop(Stack S,TreeNode* &p)
{
    if(S.top==-1)
        return -1;
    p=S.data[S.top];
    return 0;
}

void CreateTree(Tree &T)
{
    int x;
    scanf("%d",&x);
    if(x==-1)
    {
        T=NULL;
        return;
    }
    else
    {
        T=(Tree)malloc(sizeof(TreeNode));
        T->data=x;
        printf("输入%d的左结点:",x);
        CreateTree(T->lchild);
        printf("输入%d的右结点:",x);
        CreateTree(T->rchild);
    }
}

//先序遍历非递归操作
void PreOrderTree(Tree T)
{
    Stack S;
    InitStack(S);
    TreeNode *p=T;
    while(p || !isEmpty(S))
    {
        if(p)
        {
            printf("%d ",p->data);
            Push(S,p);
            p=p->lchild;
        }
        else
        {
            Pop(S,p);
            p=p->rchild;
        }
    }    
} 

//中序遍历非递归操作
void MidOrderTree(Tree T)
{
    Stack S;
    InitStack(S);
    TreeNode *p=T;
    while(p || !isEmpty(S))
    {
        if(p)
        {
            Push(S,p);
            p=p->lchild;
        }
        else
        {
            Pop(S,p);
            printf("%d ",p->data);
            p=p->rchild;
        }
    }
}  

//后序遍历非递归操作
void LatOrderTree(Tree T)
{
    Stack S;
    InitStack(S);
    TreeNode *p=T;
    TreeNode *r=NULL;//用来判断右结点是否访问过 
    while(p || !isEmpty(S))
    {
        if(p)
        {
            Push(S,p);
            p=p->lchild;    
        }    
        else
        {
            GetTop(S,p);
            if(p->rchild&&p->rchild!=r)
                p=p->rchild;    
            else
            {
                Pop(S,p);
                printf("%d  ",p->data);
                r=p;
                p=NULL;
            }
        }
    }    
} 

int main()
{
    Tree T;
    CreateTree(T);
    LatOrderTree(T);

    return 0;
    
}
复制代码

 

posted on   四马路弗洛伊德  阅读(8)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示