前言
自己最近在书写二叉树方面的内容时,在二叉树的建立部分出现了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");
}<