读书人

模板类创建二叉树解决办法

发布时间: 2012-02-08 19:52:21 作者: rapoo

模板类创建二叉树
我利用两个模板类递归创建二叉树 但是无法保存根节点地址 请帮忙
//binaryTree.h
#include <iostream>
#include <conio.h>


typedef int Status;

#define NULL 0

using namespace std;

template < class Type>

class BinaryTree;

template < class Type >

class BinaryNode
{
friend class BinaryTree ;
public:
Type data;
BinaryNode(){ leftchild = NULL; rightchild = NULL;};
BinaryNode <Type> *leftchild;
BinaryNode <Type> *rightchild;

};

template < class Type >

class BinaryTree
{
public:
BinaryTree() : root( NULL ){};
BinaryNode <Type> *CreatTree();
bool isEmpty();
BinaryNode <Type> *Parent ( BinaryNode <Type> *current );
BinaryNode <Type> *LeftChild ( BinaryNode <Type> *current );
BinaryNode <Type> *RightChild ( BinaryNode <Type> *current );
BinaryNode <Type> *GetRoot () const { return root; } ;
int depth( BinaryNode <Type> *current );
void PreOrderTraverse ();


private:
BinaryNode <Type> *Parent ( BinaryNode <Type> *start , BinaryNode <Type> *current );
BinaryNode <Type> *root;
};

//******************************************************************
//CreatTree()
//通过先序序列建立二叉树

template < class Type >

BinaryNode <Type> * BinaryTree <Type> ::CreatTree()
{
char thisch;
cout < <"please enter the order of the tree" < <endl;
thisch = getche();
cout < <endl;

if(thisch=='#')
{
return NULL;
}

else
{
root = new BinaryNode <Type> ;
root-> data = thisch;
root-> leftchild = CreatTree();
root-> rightchild = CreatTree();
return root;
}

}

[解决办法]
root = root-> leftchild;
root = root-> rightchild;
你遍历的时候用赋值语句改变了root所指向的位置了,
结果当然不是原来那个根节点了,你试试用递归来遍历,
下边的代码我没调试了,但大概思想就是那样,你自己
试试看
[code=C/C++][/code]
void BinaryTree <Type> ::PreOrderTraverse(BinaryNode <Type> *root)
{
if(root!=NULL )
{
cout < <root-> data < <endl;
PreOrderTraverse(BinaryNode <Type> *root->leftchild);
PreOrderTraverse(BinaryNode <Type> *root->rightchild);
}
else
return;
}

读书人网 >C++

热点推荐