生成二叉树----c

用c语言中最简单的方法生成一个二叉树,有注释,解释都在代码中

#include
#include//因为会用到NULL

typedef struct node{
    int val;
    struct node* left;
    struct node* right;
}Node;//定义一个树的结构体

void preorder(Node* node){
    if(node != NULL){
        printf("%d\n",node -> val);
        preorder(node -> left);
        preorder(node -> right);

    }//这里为二叉树的先序遍历,因node为指针,所以用  ->  
}


void inorder(Node* node){
    if(node != NULL){
        inorder(node -> left);
        printf("%d\n",node -> val);
        inorder(node -> right);

    }//这里为二叉树的中序遍历
}

void postorder(Node* node){
    if(node != NULL){
        postorder(node -> left);
        postorder(node -> right);
        printf("%d\n",node -> val);


    }//这里为二叉树的后序遍历
}

int main(){
    Node n1;
    Node n2;    
    Node n3;
    Node n4;//定义几个节点


    n1.val = 5;
    n2.val = 6;
    n3.val = 7;
    n4.val = 8;//节点赋值

    n1.left = &n2;
    n1.right = &n3;
    n2.left = &n4;
    n2.right = NULL;
    n3.left = NULL;
    n3.right = NULL;
    n4.left = NULL;
    n4.right = NULL;//节点按顺序连接

    preorder(&n1);
    inorder(&n1);
    postorder(&n1);
}

 

你可能感兴趣的:(数据结构)