virtual BinTreeNode<Type>* Find ( const Type&item) const;搜索 BinTreeNode<Type>* Getroot()const i return root; 取根 friend istream& operator >> (filename, Binary Tree<Type>& Tree) 重载操作:输入 friend ostream& operator <x (ostream &out, Binary Tree<Type>& Tree /重载操作:输出
virtual BinTreeNode<Type> * Find ( const Type& item ) const; //搜索 BinTreeNode<Type> *GetRoot ( ) const { return root; } //取根 friend istream& operator >> (filename, BinaryTree<Type>& Tree) //重载操作:输入 friend ostream& operator << (ostream&out, BinaryTree<Type>& Tree) //重载操作:输出 }
二叉树部分成员函数的实现 template<class Type> void Binary Tree<Type> . destroy BinTreeNode<Type> *current )t if( current!=NULL( destroy( current ->left child )i destroy( current -> right Child delete current
二叉树部分成员函数的实现 template<class Type> void BinaryTree<Type> :: destroy ( BinTreeNode<Type> *current ) { if ( current != NULL ) { destroy ( current -> leftChild ); destroy ( current -> rightChild ); delete current; } }
template<class Type> void Binary Tree <Type>:: CreateBinTree ifstream& in, BinTreeNode<Type>x& current 私有函数:以递归方式建立二叉树。 /输入结点值的顺序必须对应二叉树结点前 序遍历的顺序。并约定以输入序列中不可 能出现的值作为空结点的值以结束递归 /此值在 Revalue中。例如用“@或用“-1 示字符序列或正整数序列空结点。 Type item if(!in eof()&
template<class Type> void BinaryTree <Type> :: CreateBinTree ( ifstream& in, BinTreeNode<Type> * & current ) { //私有函数: 以递归方式建立二叉树。 //输入结点值的顺序必须对应二叉树结点前 //序遍历的顺序。并约定以输入序列中不可 //能出现的值作为空结点的值以结束递归, //此值在RefValue中。例如用“@”或用“-1” //表示字符序列或正整数序列空结点。 Type item; if ( !in.eof ( ) ) {
如图所示的二叉树的前序遍历顺序为 ABCOODE@G@@F @ E @@
如图所示的二叉树的前序遍历顺序为 A B C @ @ D E @ G @ @ F @ @ @ A B C D E G F @ @ @ @ @ @ @ @
in > item; /读入根结点的值 if (item != RefValue)i current- new BinTreeNode<Type> (item);/建立根结点 if( current=- NULL {cerr<<“存储分配错!<<endl; exit();) CreateBinTree(in, current->leftchild ) CreateBinTree( in, current->right Child else current=NULL:/封闭叶结点
in >> item; //读入根结点的值 if ( item != RefValue ) { current = new BinTreeNode<Type> ( item ); //建立根结点 if ( current == NULL ) { cerr << “存储分配错!” << endl; exit (1); } CreateBinTree ( in, current->leftChild ); CreateBinTree ( in, current->rightChild ); } else current = NULL; //封闭叶结点 } }