二叉树生成及遍历的实现

2019-11-29 15:26:57阅读 121评论 0

需求

将数组内的值,放入二叉树中并进行遍历

实现(C语言)

    #include "pch.h"  
    #include <iostream>  


    typedef struct node {  
        int data;  
        struct node *lchild, *rchild;  
    }NODE;  


    NODE* create_tree(int a[],int length) {  
        //生成树,层次存放数组中的元素,@param a[]树的元素值数组,@param length数组的长度  
        NODE* tree= (NODE*)malloc(sizeof(NODE)*length);  
        int i;  

        for (i = 0; i < length;i++) {  
            tree[i].data = a[i];  
            tree[i].lchild = NULL;  
            tree[i].rchild = NULL;  
        }  
        //为每个节点赋值,并将左、右指针设置为空  

        for (i = 0; i < length / 2 + 1; i++) {  
            if (2 * i + 1 <= length - 1) {  
                tree[i].lchild = &tree[2 * i + 1];  
            }  
            if (2 * i + 2 <= length - 1) {  
                tree[i].rchild = &tree[2 * i + 2];  
            }     
        }  
        //将父节点的左、右指针赋值  

        return tree;  
    }  

    void preorder(NODE* t) {  
        //先序遍历  
        if (NULL == t)  
            return;  
        printf("%d,", t->data);  
        preorder(t->lchild);  
        preorder(t->rchild);  
    }  

    void inorder(NODE* t) {  
        //中序遍历  
        if (NULL == t)  
            return;  
        inorder(t->lchild);  
        printf("%d,", t->data);  
        inorder(t->rchild);  
    }  

    void posorder(NODE* t) {  
        //后序遍历  
        if (NULL == t)  
            return;  
        posorder(t->lchild);  
        posorder(t->rchild);  
        printf("%d,", t->data);  
    }  

    int main()  
    {  
        int a[10] = { 0,1,2,3,4,5,6,7,8,9 };  
        NODE* b=create_tree(a, 10);  

        printf("\n先序遍历\n");  
        preorder(b);//先序遍历结果0,1,3,7,8,4,9,2,5,6  

        printf("\n中序遍历\n");  
        inorder(b);//中序遍历结果7,3,8,1,9,4,0,5,2,6  

        printf("\n后序遍历\n");  
        posorder(b);//后序遍历结果7,8,3,9,4,1,5,6,2,0  
        system("pause");  
    }

还没有评论,来说两句吧