C++ 二叉树Tree类 完整实现

 这是C++ 二叉树Tree类的实现。花了我整整一天工夫。包含了一个子类和一个树类。通过递归和链表实现的二叉树。相当标准,值得借鉴。

 

//8.(*2) 实现Tnode 二叉树类
#include <iostream>
#include <string>
class Tnode{
 friend class Tree;
 Tnode(const std::string& w):
     word(w),count(1),left(0),right(0) {}
    ~Tnode()
    {
     if(left)
      left->right=right;      
        if(right)
            right->left=left;
    }
    std::string word;
    int count;
    Tnode *left,*right;
};
class Tree{
public:
    Tree(const std::string& word){root=new Tnode(word);}
    ~Tree()
    {
        for(Tnode* p=root;p;p=p->left)
            p->~Tnode();
        root->~Tnode();
        for(Tnode* p=root;p;p=p->right)
            p->~Tnode();
        delete root;
    }
    void enter_word(const std::string&);
    void write(std::ostream& os,bool indent=true,int spaces=2);
    void write(std::ostream& os,Tnode* node,
            bool indent=true,int spaces=2);
private:
    Tnode *root;
};
void Tree::enter_word(const std::string& word)
{
 Tnode* node=root;
 while(true){
  int order=word.compare(node->word);
  if(order==0){
   ++node->count;
   break;
  }else{
   Tnode*& next=order<0?node->left:node->right;
   if(next==0){
    next=new Tnode(word);
    break;
   }else
       node=next;
  }
 }
}
void Tree::write(std::ostream& os,bool indent,int spaces)
{
 write(os,root->left,indent,spaces+2);
 if(indent)
     for(int k=0;k!=spaces;++k)
         os<<' ';
    os<<root->word
      <<"("<<root->count<<")\n";
    write(os,root->right,indent,spaces+2);
}
void Tree::write(std::ostream& os,Tnode* node,bool indent,int spaces)
{
 if(node){
     write(os,node->left,indent,spaces+2);
     if(indent)
         for(int k=0;k!=spaces;++k)
             os<<' ';
        os<<node->word
          <<"("<<node->count<<")\n";
        write(os,node->right,indent,spaces+2);
 }
}
int main()
{
 Tree t("C");
 t.enter_word("C++");
 t.enter_word("Ada");
 t.enter_word("Java");
 t.enter_word("Java++");
 t.enter_word("Pascal");
 t.enter_word("Delphi");
 t.write(std::cout);
 return 0;
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值