近来练习二叉树有关习题,一些函数使用二级指针而另一些不用的情况让人迷惑,终于想清楚了这个问题于是记录一下。
1.同一函数(下文指创建二叉树的函数)用与不用二级指针的区别
基础知识:数据结构与算法之树、二叉树(C++)以及关于建树为何用二级指针超详细不劝退教程_二叉树为什么用二级指针_源代码•宸的博客-CSDN博客
错误代码:
#include <stdio.h>
#include <iostream>
#define LEN sizeof(struct Node)
using namespace std;
struct Node{
char data;
struct Node *Lchild;
struct Node *Rchild;
};
typedef struct Node biNode;
typedef struct Node *biTree;
void create(biTree root)
{ char ch;
cin>>ch;
if(ch=='^')root=NULL;
else
{ root=(biTree)malloc(LEN);
(root)->data=ch;
create(((root)->Lchild));
create(((root)->Rchild));
}//注意反括号位置
}
void postorder(biTree root)
{
if(root)
{ postorder(root->Lchild);
postorder(root->Rchild);
cout<<root->data;
}
}
int main()
{
biTree tree;
tree=nullptr;
create(tree);
postorder(tree);
system("pause");
return 0;
}
可以看出问题出在root=(biTree)malloc(LEN);这句;因为在create函数中新开辟了空间,但由于主函数“保护地址”的作用,主函数的tree指针并没能真正指向新空间,故后续的所有操作都只是原地打转;
正确代码详见上述大佬的那篇文;
2.不同函数间比较(指create用二级而postorder不用二级)
区别在一个只向外读数(postorder),一个却要改写(create)