首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

2叉树非递归遍历 求拍解决思路

2012-06-09 
2叉树非递归遍历 求拍C/C++ code#include stdio.h#include stacktypedef struct BiNode {int dataBiN

2叉树非递归遍历 求拍

C/C++ code
#include <stdio.h>#include <stack>typedef struct BiNode {    int data;    BiNode* lchild;    BiNode* rchild;}BiNode,BiTree;enum Tags{left,right};BiTree*  CreateTree(BiTree** t){    int data;    scanf("%d",&data);    if (data!=100)    {        (*t)=new BiNode();        (*t)->data = data;        CreateTree(&((*t)->lchild));        CreateTree(&((*t)->rchild));    }    return *t;}void ReleaseTree(BiTree* t){    if (t)    {        ReleaseTree(t->lchild);        ReleaseTree(t->rchild);        delete t;    }}void InorderTraverseEX(BiTree* p){        std::stack<BiNode*> s;    BiTree* t = p;    while (t||!s.empty())    {        if (t)        {            s.push(t);            t=t->lchild;        }        else        {            printf("%d\n",s.top()->data);            t=s.top();            t=t->rchild;            s.pop();        }    }}void PreorderTraverseEX(BiTree* t){    BiTree* p = t;    std::stack<BiTree*> s;    while (p||!s.empty())    {        if (p)         {            printf("%d\n",p->data);            s.push(p);            p=p->lchild;        }        else        {            p=s.top();            p= p->rchild;            s.pop();        }    }    }void PostorderTraverseEX(BiTree* t){    BiTree* p = t;    std::stack<BiTree*> s;    std::stack<Tags> sTag;    while (true)    {        while (p!=NULL)        {            s.push(p);            p=p->lchild;            sTag.push(left);        }        while(sTag.top()==right)               //使用while 是为了让 节点不用再向左延伸,以免重复。        {                        printf("%d\n",s.top()->data);            p=s.top();                         //这句强调的是 p 需要指向刚刚访问过的节点            s.pop();            sTag.pop();            if (s.empty()||sTag.empty())                return;        }            sTag.pop();            sTag.push(right);            p=s.top()->rchild;                        }}int main(){    BiTree* t = new BiNode();    t = CreateTree(&t);    printf("先序遍历\n");    PreorderTraverseEX(t);    printf("中序遍历\n");    InorderTraverseEX(t);    printf("后序遍历\n");    PostorderTraverseEX(t);    ReleaseTree(t);    return 0;}


[解决办法]
恩,写的好!

热点排行