树啊……树啊……

Date:  2011/8/25   Sort:  编程开发 11961 Views / 13 Comments 

  从昨天深夜到今天中午,总算把二叉树生成算法弄出来了。

  怎么觉得自己这么笨捏……5个小时……要是竞赛考试的时候这样

  代码贴出来,供大家参考:

  {注:输入文件格式:

        二叉树:1(2(3,),3(,4))

        应写为:1 2 3 e e e 3 e 4 e e (每行一个数,e表示前一结点没有左子结点或右子结点);}

#include <fstream>
#include <iostream>
using namespace std;
int layer=0;
ifstream filein;
struct node
{
        float data;
        node *left;
        node *right;
};
void preOrder_tree(node *p)
{
     if (p->left!=NULL) preOrder_tree(p->left);
     cout<<p->data<<"-";
     if (p->right!=NULL) preOrder_tree(p->right);
}
void inOrder_tree(node *p)
{
     cout<<p->data<<"-";
     if (p->left!=NULL) inOrder_tree(p->left);    
     if (p->right!=NULL) inOrder_tree(p->right);
}
void postOrder_tree(node *p)
{
     if (p->left!=NULL) postOrder_tree(p->left);
     if (p->right!=NULL) postOrder_tree(p->right);
     cout<<p->data<<"-";
}

void insert_tree(node* &p)
{
      cout<<"Getting data from file 'tree_in.dat'. Now in layer "<<layer<<": ";
      while(filein.peek()=='\n')
      {                        
                         filein.get();
                         if (filein.peek()==EOF) return;
      }
      if (filein.peek()=='e')
      {
           cout<<"    User Terminate!"<<endl;
           filein.get();
           p=NULL;
      }
      else
      {
           p=new node;           //Create a node and initialize
           filein>>p->data;//Store float-data from string-stream
           cout<<p->data<<endl;
           layer++;//Depth++
             insert_tree(p->left);
           insert_tree(p->right);
           layer--;
      }
}
                
int main()
{
    node *root=NULL;
    filein.open("tree_in.dat");   
    insert_tree(root);//Make a tree
    filein.close();
    if (root!=NULL)
    {                  
                   cout<<endl<<"Now going to output>>>>>>>>"<<endl;cin.get();
                   preOrder_tree(root);cout<<endl;
                   inOrder_tree(root);cout<<endl;                  
                   postOrder_tree(root);cout<<endl;
    }
    cin.clear();cin.get();
    return 0;   
}

转载本站文章请注明,转载自:WTZ的小博[ http://wiblog.net/]
知识共享许可协议 本作品采用知识共享署名 4.0 国际许可协议进行许可。

更多

评论(13)条

Cristiane
2013-07-20 10:23
What a joy to find soenome else who thinks this way.
Pull Ralph Lauren
2012-12-17 20:06
All the the worst option to miss one is to be as well as appropriately beside them comprehending you possibly can‘to ask them to.
catalogue la redoute
2012-12-17 20:06
In the would take care of your magic using an enemy, say to that via the anyone.
promo la redoute
2012-12-17 20:06
Affection will be hectic problem to the reality along with increase of whatever they have a passion for.
reduc la redoute
2012-12-17 20:05
An actual buddie any who also overlooks all of your backsliding as well as tolerates all of your successes.