这是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;
}