博客首页 注册 建议与交流 排行榜 加入友情链接
推荐 投诉 搜索: 帮助

取个标题想半天

没有什么东西是可以不通过努力奋斗来获得
luojingqing.cublog.cn


二叉树的构造方法及前后中序遍历算法

#include <iostream>
using namespace std;
struct bitree
{
char data;
bitree *lchild;
bitree *rchild;
};

bitree *create()      //构造树
{
char ch;
cout<<"请输入节点(结束时用#表示):"<<endl;
cin>>ch;
bitree *root,*p,*s[100];
int front=1;
   
while(ch!='#')
{
      p=NULL;
   
  
    p=new bitree;
    p->data=ch;
       p->lchild=NULL;
    p->rchild=NULL;
   

   s[front]=p;
   if(front==1) {root=s[front];front++;}
        else
   {  
   
     if(front%2==0) {s[front/2]->lchild=s[front];front++;}
     else if(front%2==1)
     {s[(front-1)/2]->rchild=s[front];front++;}
  
   }
   cin>>ch;
  
}
return root;
}

void preorder(bitree *root)       //先序遍历
{
bitree *p;
p=root;
if(p!=NULL)
{
   cout<<p->data<<" ";
   preorder(p->lchild);
   preorder(p->rchild);
}
}
void inorder(bitree *root)      // 中序遍历
{
   bitree *p;
   p=root;
   if(p!=NULL)
   {inorder(p->lchild);
   cout<<p->data<<" ";
   inorder(p->rchild);
   }

}

void postorder(bitree *root)      //后序遍历
{
bitree *p;
p=root;
if(p!=NULL)
{
   postorder(p->lchild);
   postorder(p->rchild);
   cout<<p->data<<" ";
}
}

void main()
{
   bitree *root;
   root=create();
   preorder(root);
   cout<<endl;
   inorder(root);
   cout<<endl;
   postorder(root);
   cout<<endl;
  
}

发表于: 2008-04-07 ,修改于: 2008-04-07 15:59,已浏览140次,有评论0条 推荐 投诉


网友评论

发表评论