二叉搜索树的问题,总是运行错误
struct Node
{
int key;
Node *p;
Node *left;
Node *right;
};
class BinarySearchTree
{
private:
Node *root;
Node *temp;
public:
Node* Root();
BinarySearchTree();
~BinarySearchTree();
void InorderWalkTree(Node *T);
void PreorderWalkTree(Node *T);
void PostorederWalkTree(Node *T);
Node* Search(int k);
Node* Minmum(Node *x);
Node* Maxmum(Node *x);
Node* Predecessor(Node *x);
Node* Successor(Node *x);
void Insert(int x);
void Transplant(Node *u,Node *v);
void Delete(int x);
};
void BinarySearchTree::Insert(int value)
{
Node *y,*x;
y=NULL;
x=root;
while(x!=NULL)
{
y=x;
if(x->key>value)
x=x->left;
if(x->key<value)
x=x->right;
}
if(y=NULL)
{
root=new Node;
root->key=value;
}
else if(x==y->left)
{
y->left=new Node;
y->left->p=y;
y->left->key=value;
}
else
{
y->right=new Node;
y->right->p=y;
y->right->key=value;
}
}
int main()
{
BinarySearchTree T;
T.Insert(5);
//T.Insert(6);
//T.Insert(7);
//T.Insert(1);
//T.Insert(4);
//T.Insert(3);
return 0;
}
root应该在构造函数中置空,如下:
BinarySearchTree::BinarySearchTree():root(NULL){}
或者
BinarySearchTree::BinarySearchTree(){root = NULL;}
if(y=NULL) //少写等号了吧 建议把NULL写前面,这样少写等号会报错:if(NULL == y)
{
root=new Node;
root->key=value;
}
[解决办法]
实际工程中不要自己写了,STL中有成熟的二叉树