您的位置:首页 > 其它

二叉树的遍历 不知道哪里有问题 求指点

2013-10-04 16:19 204 查看
#include<iostream>

using namespace std;

struct BiNode

{

char data;

BiNode *lchild,*rchild;

};

struct element

{

BiNode *ptr;

int flag;

};

class BiTree

{

public:

BiTree(){root=NULL;}

BiTree(BiNode *root);

// ~BiTree();

void preorder(BiNode *root);

void inorder(BiNode *root);

void postorder(BiNode *root);

void levelorder(BiNode *root);

//void release(BiNode *root);

private:

BiNode *root;

void creat(BiNode *root);

};

void BiTree::preorder(BiNode *root)

{

int top=-1;

BiNode *s=new BiNode;

while(root!=NULL||top!=-1)

{

while(root!=NULL)

{

cout<<root->data;

s[++top]=*root;

root=root->lchild;

}

if(top!=-1)

{

*root=s[top--];

root=root->rchild;

}

}

}

void BiTree::inorder(BiNode *root)

{

int top=-1;

BiNode *s=new BiNode;

while(root!=NULL||top!=-1)

{

while(root!=NULL)

{

s[++top]=*root;

root=root->lchild;

}

if(top!=-1)

{

*root=s[top--];

cout<<root->data;

root=root->rchild;

}

}

}

void BiTree::postorder(BiNode *root)

{

int top=-1;

element *s=new element;

while(root!=NULL||top!=-1)

{

while(root!=NULL)

{

top++;

s[top].ptr=root;

s[top].flag=1;

root=root->lchild;

}

while(top!=-1&&s[top].flag==2)

{

root=s[top--].ptr;

cout<<root->data;

}

if(top!=-1)

{

s[top].flag=2;

root=s[top].ptr->rchild;

}

}

}

/*void BiTree::levelorder(BiTree *root)

{

int front=rear=0;

if(root==NULL)return ;

BiNode *Q=new BiNode;

Q[++rear]=root;

BiNode *q;

while(front!=rear)

{

q=Q[++front];

cout<<q->data;

if(q->lchild!=NULL)

Q[++rear]=q->lchild;

if(q->rchild!=NULL)

Q[++rear]=q->rchild;

}

}

*/

void BiTree::creat(BiNode *root)

{

char ch;

cin>>ch;

if(ch=='#')

root=NULL;

else

{

root=new BiNode;

root->data=ch;

creat(root->lchild);

creat(root->rchild);

}

}

BiTree::BiTree(BiNode *root)

{

creat(root);

}

/*void BiTree::release(BiNode *root)

{

if(root!=NULL)

{

release(root->lchild);

release(root->rchild);

delete root;

}

}

/*BiTree::~BiTree(BiNode *root)

{

release(root);

}*/

int main()

{

BiNode *q=new BiNode;

BiTree s(q);

s.inorder(q);

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: