1 因为关键字,折腾很久,为何定义的结构体总是说没有这个定义,原来问题出现在没有用关键字typedef,这个关键字通俗点说就是别名的意思,可用用定义的别名来定义其他的变量或函数,当需要改变这个别名类型的时候,只要修改typedef定义就可以做到一改全改的目的,不用一个个去改变类型了。
2 今天因为在函数内部申请的内存,回到原函数是,申请的内存已经被释放了,百思不得其解,终于看到C++的伟大之处,使用引用&操作符,可以解决这个问题,Mark一下。
二叉查找树代码
#include <iostream>
using namespace std;
typedef int elemType;
typedef struct biNode
{
struct biNode *parent,*left,*right;
elemType key;
}*biTree;
int insertNode(biTree & root,elemType key)
{
biTree x,y=NULL;
biTree z=new biNode;
z->key=key;
z->parent=z->right=z->left=NULL;
x=root;
while (x!=NULL)
{
y=x;
if (z->key<y->key)
x=x->left;
else
x=x->right;
}
z->parent=y;
if (y==NULL)
root=z;
else if (z->key<y->key)
y->left=z;
else
y->right=z;
return 0;
}
biTree treeSearch(biTree & root,elemType k)
{
if (root==NULL||k==root->key)
return root;
if (k<root->key)
return treeSearch(root->left,k);
else
return treeSearch(root->right,k);
}
biTree minNode(biTree root)
{
biTree x=root;
while (x->left==NULL)
x=x->left;
return x;
}
biTree successorNode(biTree root)
{
biTree x=root;
biTree y;
if (x->right!=NULL)
return minNode(x->right);
y=x->parent;
while (y!=NULL&&x==y->right)
{
x=y;
y=y->parent;
}
return y;
}
biTree delNode(biTree & root,elemType k)
{
biTree x=NULL,y=NULL;
biTree z=treeSearch(root,k);
if (z->left==NULL||z->right==NULL)
{
y=z;
}
else
y=successorNode(z);
if (y->left==NULL)
{
x=y->left;
}
else
x=y->right;
if (x!=NULL)
{
x->parent=y->parent;
}
if (y->parent==NULL)
{
root=x;
}
else if (y=y->parent->left)
{
y->parent->left=x;
}
else
y->parent->right=x;
if (y!=z)
{
z->key=y->key;
}
return y;
}
void InorderTreeWalk(biTree & root)
{
if (root!=NULL)
{
InorderTreeWalk(root->left);
cout<<root->key<<"-->";
InorderTreeWalk(root->right);
}
}
int main()
{
biTree root=NULL;
int num;
cin>>num;
for (int i=0;i<num;i++)
{
int temp;
cout<<"input the "<<i+1<<" num :";
cin>>temp;
insertNode(root,temp);
}
InorderTreeWalk(root);
if (treeSearch(root,10)->key==10)
{
cout<<"succeed!"<<endl;
}
else
insertNode(root,10);
InorderTreeWalk(root);
delNode(root,10);
InorderTreeWalk(root);
return 0;
}