二叉树的创建和遍历

//创建二叉树

bitree *create_bitree(int i, int n)     //i=1, n为节点的个数

{
    if (i == 0) return ;
    bitree *root = (bitree*)malloc(sizeof(bitree));
    root->data = i;

    if (2*i <= n) //如果存在左子树
    {
        root->lchild = create_bitree(2*i, n);
    }
    else
        root->lchild = NULL;

    if (2*i+1 <= n) //如果存在右子树
    {
        root->rchild = create_bitree(2*i+1, n);
    }
    else
        root->rchild = NULL;
    
    return root;

}


//先序遍历二叉树

void preorder(bitree *root)
{
    if (NULL == root)
        return ;
    printf("%d ", root->data);
    preorder(root->lchild);
    preorder(root->rchild);
}


//层次遍历二叉树,用队列实现

void layer_order(bitree *root)
{
    bitree *temp;
    queue qu;
    init_queue(&qu);
    join_queue(&qu, root);

    while (!empty_queue(&qu))
    {
        temp = out_queue(&qu);
        printf("%d ", temp->data);

        if (temp->lchild)
            join_queue(&qu, temp->lchild);
        if (temp->rchild)
            join_queue(&qu, temp->rchild);

    }
    return ;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值