前言
自己最近在书写二叉树方面的内容时,在二叉树的建立部分出现了bug,想了很久才明白,在这里记录下,以后不要再犯
代码
先写几个递归建立二叉树的代码,再附一个非递归建立二叉树的方法
#include <stdio.h>
#include <stdlib.h>
typedef struct tree{
int data;
struct tree * left;
struct tree * right;
}Bitree, *pBitree;
void Preorder(pBitree root){
if (root){
printf("%d\n", root->data);
Preorder(root->left);
Preorder(root->right);
}
else
return;
}//先序遍历二叉树
第一种
pBitree CreatTree(){
pBitree root;
int a;
printf("enter\n");
scanf("%d", &a);
if (a){
root = (pBitree)malloc(sizeof(Bitree));
(root)->data = a;
root->left=CreatTree();
root->right=CreatTree();
}
else{
root = NULL;
}
return root;
}
//这种代码比较简洁
int main(){
pBitree p;
p = CreatTree();
Preorder(p);
system("pause");
}
第二种
void Creat_Tree(

本文记录了在建立二叉树过程中遇到的问题和解决方案。首先展示了三种递归创建二叉树的C/C++代码,接着讨论了使用引用避免第二种方法中的指针问题。然后,解释了一种非递归创建二叉树的方法,其灵感来源于操作系统处理递归时的栈操作。文中还提到了一个常见错误,即释放内存后未能正确设置指针为空,导致潜在的问题。
1802

被折叠的 条评论
为什么被折叠?



