编辑代码


#include <malloc.h>
#include <stdio.h>
#include <string.h>
#define maxn 10005
struct Tree{
    int *val;
};
void initTree(Tree* tree){
    tree->val = (int*)malloc(sizeof(int)*maxn*4);
    memset(tree->val,-1,sizeof(int)*maxn*4);
}

void insertNode(Tree* tree,int node){
    int now = 1;
    while(tree->val[now] != -1){
        if(node < tree->val[now]){
            now = now*2;
        }
        else{
            now = now*2+1;
        }
    }
    tree->val[now] = node;
}
void preorder(Tree* tree,int index=1){
    if(tree->val[index] == -1)return;
    printf("%d ",tree->val[index]);
    preorder(tree,index*2);
    preorder(tree,index*2+1);
}
void inorder(Tree *tree, int index = 1) {
    if (tree->val[index] == -1)
        return;
    inorder(tree, index * 2);
    printf("%d ", tree->val[index]);
    inorder(tree, index * 2 + 1);
}
void postorder(Tree *tree, int index = 1) {
    if (tree->val[index] == -1)
        return;
    postorder(tree, index * 2);
    postorder(tree, index * 2 + 1);
    printf("%d ", tree->val[index]);
}
void bfs(Tree *tree){
    int q[maxn] = {1};
    int front=0,rear=1;
    while(front != rear){
        int now = q[front++];
        printf("%d ",tree->val[now]);
        if (tree->val[now * 2] != -1) {
            q[rear++] = now * 2;
        }
        if (tree->val[now * 2 + 1] != -1) {
            q[rear++] = now * 2 + 1;
        }
    }
}
int main(){
    int n;
    scanf("%d",&n);
    Tree *tree;
    initTree(tree);
    for(int i=1;i<=n;i++){
        int temp;
        scanf("%d",&temp);
        insertNode(tree, temp);
    }
    preorder(tree);
    puts("");
    inorder(tree);
    puts("");
    postorder(tree);
    puts("");
    bfs(tree);
    return 0;
}