二叉树--非递归实现

#include<iostream>
#include<stack>
#include<stdio.h>
#include<stdlib.h>
#define ElemType char
using namespace std;

typedef struct BiTNode{
    ElemType data;
    struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;

int createBiTree(BiTree *t)
{
    char ch;
    ch = getchar();
    if(ch==' ')
        (*t) = NULL;
    else
    {
        (*t) = (BiTNode*)malloc(sizeof(BiTNode));
        if(!(*t))
            return 0;
        (*t)->data = ch;
        createBiTree(&(*t)->lchild);
        createBiTree(&(*t)->rchild);
    }
    return 1;
}

void preOrderDisplay(BiTree t)
{
    cout<<"*************preOrderDisplay***********"<<endl;
    stack<BiTree> s;
    if(!t)
    {
        cout<<"empty tree"<<endl;
        return;
    }
    s.push(t);
    while(!s.empty())
    {
        BiTree tmp = s.top();
        cout<<tmp->data;
        s.pop();
        if(tmp->rchild!=NULL)
            s.push(tmp->rchild);
        if(tmp->lchild!=NULL)
            s.push(tmp->lchild);
    }
    
}

void inOrderDisplay(BiTree t)
{
    cout<<"\n************inOrderDisplay************"<<endl;
    if(!t)
    {
        cout<<"empty tree"<<endl;
        return;
    }
    stack<BiTree> s;
    BiTree curr = t; 
    
    while(curr!=NULL||!s.empty())
    {
        while(curr!=NULL) // 把节点的左子节点全部入栈
        {
            s.push(curr);
            curr = curr->lchild;
        }
        
        // 然后边出栈边输出边入右节点
        if(!s.empty())
        {
            BiTree tmp = s.top();
            cout<<tmp->data;
            s.pop();
            curr = tmp->rchild;
        }
    }    
    
}

void postOrderDisplay(BiTree t)
{
    cout<<"\n**************postOrderDisplay**************"<<endl;
    if(!t)
        return;
    stack<BiTree> s;
    BiTree curr = t;
    BiTree pre = NULL;

    while(curr!=NULL||!s.empty())
    {
        while(curr!=NULL) // 先左节点全部入栈
        {
            s.push(curr);
            curr = curr->lchild;
        }

        curr = s.top();  
        if(curr->rchild == NULL||curr->rchild == pre) // 判断当前节点是否有右孩子或者当前节点的右孩子是否等于上次访问节点
        {
            cout<<curr->data;
            s.pop();
            pre = curr;
            curr = NULL;
        }    
        else // 有右孩子,需要入栈
            curr = curr->rchild;
    }
}

int main()
{
    BiTree t;
    int creRes = createBiTree(&t);
    cout<<"*******state of creating bitree : "<<creRes<<endl;
    preOrderDisplay(t);
    inOrderDisplay(t);
    postOrderDisplay(t);
    return 1;
}

 

posted @ 2016-01-26 22:15  第九剑  阅读(203)  评论(0编辑  收藏  举报