二叉树的链式存储结构

只复习一下二叉树的遍历,其他的以后再看

表示

/* bt_data_t for bi tree */
typedef char bt_data_t;
#define NULL_DATA    '\0'

/* data_t for queue which will hold the pointer of bitree_t */
typedef void *data_t;

typedef struct tree_node_t {
    bt_data_t         data;
    struct tree_node_t     *lchild, *rchild;
} bitree_t;

实现

bitree_t *CreateBitree(int i, bt_data_t data[], int n)
{
    bitree_t *root;
    int j;
    
    root = (bitree_t *)malloc(sizeof(bitree_t));
    root->data = data[i];
    
    j = 2 * i;
    if ((j <= n) && (data[j] != NULL_DATA)) {
        root->lchild = CreateBitree(j, data, n);
    } else {
        root->lchild = NULL;
    }
    
    j = 2 * i + 1;
    if ((j <= n) && (data[j] != NULL_DATA)) {
        root->rchild = CreateBitree(j, data, n);
    } else {
        root->rchild = NULL;
    }
    return root;
}

void PreOrder(bitree_t *root)
{
    if (NULL == root) return;
//do    
    printf("%c ", root->data);
    PreOrder(root->lchild);
    PreOrder(root->rchild);
    return;
}

void InOrder(bitree_t *root)
{
    if (NULL == root) return;
    InOrder(root->lchild);
//do
    printf("%c ", root->data);
    InOrder(root->rchild);
    return;
}

void PostOrder(bitree_t *root)
{
    if (NULL == root) return;
    PostOrder(root->lchild);
    PostOrder(root->rchild);
//do
    printf("%c ",root->data);
    return;
}

void NoOrder(bitree_t *root)
{
    linkqueue_t *lq;
    
    /* create queue */
    lq = CreateEmptyLinkqueue();
    
    /* root node enters queue */
    EnQueue(lq, root);
    
    while (!EmptyLinkqueue(lq)) {
        
        DeQueue(lq, (data_t *)(&root));
        printf("%c ", root->data);
        
        if (root->lchild != NULL) {
            EnQueue(lq, root->lchild);
        }
        
        if (root->rchild != NULL) {
            EnQueue(lq, root->rchild);
        }
    }

    return;
}

测试代码

int main()
{
    bitree_t *root;

    bt_data_t bt_array[] = {0, /* reserved [0] */
        'A', 'B', 'C', 'D','E', 0, 'F', 0, 0, 'G', 'H', 0, 0, 'I'
        };

    root = CreateBitree(
        1, 
        bt_array, 
        sizeof(bt_array)/sizeof(bt_data_t) - 1);
    
    printf("PreOrder  : ");
    PreOrder(root);
    printf("\n");

    printf("InOrder   : ");
    InOrder(root);
    printf("\n");

    printf("PostOrder : ");
    PostOrder(root);
    printf("\n");

    printf("NoOrder   : ");
    NoOrder(root);
    printf("\n");

    return 0;
}

结果

PreOrder  : A B D E G H C F I 
InOrder   : D B G E H A C I F 
PostOrder : D G H E B I F C A 
NoOrder   : A B C D E F G H I 

 

转载于:https://www.cnblogs.com/vsyf/p/4921481.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值