#include <stdio.h>
typedef struct Node {
int data;
struct Node* lchild;
struct Node* rchild;
}Node;
//使用数组存放数据,注意是按照一层一层的排列,-1代表为空
int array[] = {1,2,3,4,5,6,7};
//构建二叉树
void createTree(Node **node,int index) {
if (index <= (sizeof(array)/sizeof(int)) ){
if (array[index-1] == -1) {
*node = NULL;
return;
}
else {
*node = (Node*)malloc(sizeof(Node));
(*node)->data = array[index-1];
createTree(&((*node)->lchild), index * 2);
createTree(&((*node)->rchild), index * 2 + 1);
}
}
else {
*node = NULL;
return;
}
}
void preOrder(Node* node) {
if (node != NULL) {
printf("%d ", node->data);
preOrder(node->lchild);
preOrder(node->rchild);
}
else {
return;
}
}
void midOrder(Node* node) {
if (node != NULL) {
midOrder(node->lchild);
printf("%d ", node->data);
midOrder(node->rchild);
}
else {
return;
}
}
void afterOrder(Node* node) {
if (node != NULL) {
afterOrder(node->lchild);
afterOrder(node->rchild);
printf("%d ", node->data);
}
else {
return;
}
}
int main(int argc, char* args[]){
Node* node_t;
createTree(&node_t,1);
preOrder(node_t);
printf("
");
midOrder(node_t);
printf("
");
afterOrder(node_t);
return 0;
}