编译可以通过,但是一运行就崩溃了
「已注销」 2017-11-06 07:18:36 // 二叉搜索树.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream.h>
#include<stdlib.h>
typedef int ElemType;
struct BTreeNode{
ElemType data;
BTreeNode*left;
BTreeNode*Right;
};
void InitBTree(BTreeNode*& BT)
{
BT=NULL;
}
void Insert(BTreeNode*& BST,const ElemType&item)
{
if(BST==NULL)
{
BTreeNode*p=new BTreeNode;
p->data=item;
p->left=p->Right=NULL;
BST=p;
}
else if(item<BST->data)
Insert(BST->left,item);
else
Insert(BST->Right,item);
}
void CreateBSTree(BTreeNode*& BST,ElemType a[ ],int n)
{
BST=NULL;
for(int i=0;i<n;i++)
Insert(BST,a[i]);
}
void PrintBTree(BTreeNode*BT)
{
if(BT!=NULL)
{
cout<<BT->data;
if(BT->left!=NULL||BT->Right!=NULL)
cout<<'(';
PrintBTree(BT->left);
if(BT->Right!=NULL)
cout<<',';
PrintBTree(BT->Right);
cout<<')';
}
}
int DepthBTree(BTreeNode*BT)
{
if(BT==NULL)
return 0;
else{
int dep1=DepthBTree(BT->left);
int dep2=DepthBTree(BT->Right);
if(dep1>dep2)
return dep1+1;
else
return dep2+1;
}
}
void InOder(BTreeNode*BT)
{
InOder(BT->left);
cout<<BT->data;
InOder(BT->Right);
}
bool Find1(BTreeNode*BST,ElemType&item)
{
while(BST!=NULL){
if(item==BST->data){
item=BST->data;
return true;
}
else if(item<BST->data)
BST=BST->left;
else
BST=BST->Right;
}
return false;
}
void Insert1(BTreeNode*&BST,const ElemType& item)
{
BTreeNode*t=BST,*parent=NULL;
while(t!=NULL){
parent=t;
if(item<t->data)
t=t->left;
else
t=t->Right;
}
BTreeNode*p=new BTreeNode;
p->data=item;
p->left=p->Right=NULL;
if(parent==NULL)
BST=NULL;
else if(item<parent->data)
parent->left=p;
else parent->Right=p;
}
bool Delete(BTreeNode*&BST,const ElemType&item)
{
if(BST==NULL)
return false;
if(item<BST->data)
return Delete(BST->left,item);
if(item>BST->data)
return Delete(BST->Right,item);
BTreeNode*temp=BST;
if(BST->left==NULL)
{
BST=BST->Right;
delete temp;
return true;
}
else if(BST->Right==NULL)
{
BST=BST->left;
delete temp;
return true;
}
else{
if(BST->left->Right==NULL){
BST->data=BST->left->data;
return Delete(BST->left,BST->left->data);
}
else{
BTreeNode* p1=BST,*p2=BST->left;
while(p2->Right!=NULL){
p1=p2;
p2=p2->Right;
}
BST->data=p2->data;
return Delete(p1->Right,p2->data);
}
}
}
void ClearBTree(BTreeNode *&BT)
{
if(BT!=NULL)
{
ClearBTree(BT->left);
ClearBTree(BT->Right);
delete BT;
BT=NULL;
}
}
void main()
{
ElemType x;
BTreeNode* bst;
InitBTree(bst);
ElemType a[10]={30,50,20,40,25,70,54,23,80,92};
CreateBSTree(bst,a,10);
PrintBTree(bst);
cout<<endl;
cout<<"深度:";
cout<<DepthBTree(bst)<<endl;
cout<<"中序遍历二叉搜索树:";
InOder(bst);
cout<<endl;
cout<<"输入带查找整数:";
cin>>x;
if(Find1 (bst,x))
cout<<"查找元素"<<x<<"成功!"<<endl;
else
cout<<"查找元素"<<x<<"失败!"<<endl;
cout<<"输入一个待插入结点:";
cin>>x;
Insert1(bst,x);
cout<<"输入一个待删除结点:";
if(Delete(bst,x))
cout<<"删除元素"<<x<<"成功!"<<endl;
else
cout<<"删除元素"<<x<<"失败!"<<endl;
PrintBTree(bst);
cout<<endl;
cout<<"中序遍历二叉搜索树:";
InOder(bst);
cout<<endl;
ClearBTree(bst);
}