由于要面对考试,重写一下二叉树的构建,结果各种出错,整理一下
前期我陷入对指针应用的迷惑。
错误及其离谱
例如:
void CreateTree(tree *&root,int n)
{
while (root)
root=root->child[n>root->power];//明明使用了引用,却一直在改变root值,
//显然会导致主函数中的root指向发生改变,
//我却还傻傻的以为用了个骚操作root->child[n>root->power],很牛逼的样子
//真是个逗比。
Bound(root,n);
}
后期逐渐意识到引用的使用及自己理解的错误
开始用递归,不过还是错误百出。
敲码累了的同学,可以开心一下。
- 第一种
void Bound(tree *& root,int n)
{
root=(tree *)malloc(sizeof(tree));
root->power=n;
root->child[0]=root->child[1]=0;
}//上面那个函数没错主要在CreateTree中
void CreateTree(tree *&root,int n)
{
while(root)//不知道咋想的,循环,加递归,后面还有一个操作,这三行错的真是秀。
CreateTree(root->child[n>root->power],n);
Bound(root,n);
}
- 第二种
while(root)//加了个if,可循环加递归,依旧在那里,真是无语
CreateTree(root->child[n>root->power],n);
if (root==NULL)
Bound(root,n);
- 第三种
if (root==NULL)//好不容易改对了
Bound(root,n);
else
CreateTree(root->child[n>root->power],n);
二叉排序树的删除操作
void DeleteTreeNode(tree *&root,int n)
{
tree *te=root;
//首先找到要被删除的节点
while(te->child[n>te->power]->power!=n&&te!=NULL)
te=te->child[n>te->power];
//跳出循环,得到节点,到底是不是还要判断一下
if (te==NULL)
return;
else
{
tree *te2=te->child[n>te->power];//te2位于将被删除的节点。
//开始删除操作。
//分为四种情况
//第一种,te2的左右子树均为空
if (te2->child[0]==NULL&&te2->child[1]==NULL)
delete(te2);
//第二种情况,te2左子树为空,右子树存在
else if (!te2->child[0])
te->child[n>te->power]=te2->child[1];
//第三种,te2右子树为空,左子树存在
else if (!te2->child[1])
te->child[n>te->power]=te2->child[0];
//第四种,te2左右子树都存在。
else
{
tree *te3=te2->child[0];
//找到将要被删除左子树的最大值,换到被删除节点上去
while(te3->child[1]!=NULL)
{
te2=te3;
te3=te3->child[1];
}
te->child[n>te->power]->power=te3->power;
if (te2==te->child[n>te->power])
te2->child[0]=te3->child[0];
else
te2->child[1]=te3->child[0];
delete(te3);
}
}
}