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

来源:互联网 发布:go编程语言 编辑:程序博客网 时间:2024/05/01 07:00
#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;
}
原创粉丝点击