非递归中序先序遍历

#include<stdio.h>
#include<stdlib.h>
#define NULL 0
#define MAXSIZE 100

typedef struct BTNode
{
    struct BTNode *lchild,*rchild;
    int data;
}BTNode,*btnode;

void createBtree(btnode &T)
{
    int t;
    scanf("%d",&t);
    if(t==0)
        T=NULL;
    else
    {
        T=(btnode)malloc(sizeof(BTNode));
        T->data=t;
        createBtree(T->lchild);
        createBtree(T->rchild);
    }
}

void preOrder(btnode &p)
{
    btnode stack[MAXSIZE];
    int top=-1;
    btnode q;
    if(p)
    {
        stack[++top]=p;
        while(top!=-1)
        {
            q=stack[top--];
            printf("%d ",q->data);
            if(q->rchild)
                stack[++top]=q->rchild;
            if(q->lchild)
                stack[++top]=q->lchild;
        }
    }
}

void inOrder(btnode &p)
{
    btnode stack[MAXSIZE];
    int top=-1;
    if(p)
    {
        while(p!=NULL||top!=-1)
        {
            while(p)
            {
                stack[++top]=p;
                p=p->lchild;
            }
            if(top!=-1)
            {
                p=stack[top--];
                printf("%d ",p->data);
                p=p->rchild;
            }
        }   
    }
}



void main()
{
    btnode T;
    int key;
    createBtree(T);
    printf("preorder trave: ");
    preOrder(T);
    printf("\ninorder trave: ");
    inOrder(T);
    printf("\n");
}

你可能感兴趣的:(二叉树)