数据结构:完全二叉树(递归实现)

       如果完全二叉树的深度为h,那么除了第h层外,其他层的节点个数都是满的,第h层的节点都靠左排列。

       完全二叉树的编号方法是从上到下,从左到右,根节点为1号节点,设完全二叉树的节点数为sum,某节点编号为i,

       当2*i <= sum时,有左孩子,其编号为2*i,否则没有左孩子,本身为叶节点。

       当2*i+1 <= sum时,有右孩子,其编号为2*i+1,否则没有右孩子。

tree.h

/*===============================================
*   文件名称:tree.h
*   创 建 者:cxy     
*   创建日期:2024年01月23日
*   描    述:
================================================*/
#ifndef _TREE_H
#define _TREE_H

#include <stdio.h>
#include <stdlib.h>

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

Ptree init(int i,int sum); //i为节点编号,sum为总数
int preorder(Ptree root);  //先序遍历
int inorder(Ptree root);   //中序遍历
int postorder(Ptree root); //后序遍历

#endif

tree.c

/*===============================================
*   文件名称:tree.c
*   创 建 者:cxy     
*   创建日期:2024年01月23日
*   描    述:
================================================*/
#include "tree.h"

Ptree init(int i,int sum)
{
    Ptree root = malloc(sizeof(Tree));
    root->data = i;
    if(2*i <= sum)
    {
        root->lchild = init(2*i,sum);
    }
    else
    {
        root->lchild = NULL;
    }
    if(2*i+1 <= sum)
    {
        root->rchild = init(2*i+1,sum);
    }
    else
    {
        root->rchild = NULL;
    }
    return root;
}

int preorder(Ptree root)
{
    if(NULL == root)
        return 0;
    printf("%d ",root->data);
    preorder(root->lchild);
    preorder(root->rchild);
    return 0;
}

int inorder(Ptree root)
{
    if(NULL == root)
        return 0;
    inorder(root->lchild);
    printf("%d ",root->data);
    inorder(root->rchild);
    return 0;
}

int postorder(Ptree root)
{
    if(NULL == root)
        return 0;
    postorder(root->lchild);
    postorder(root->rchild);
    printf("%d ",root->data);
    return 0;
}

main.c

/*===============================================
*   文件名称:main.c
*   创 建 者:cxy     
*   创建日期:2024年01月23日
*   描    述:
================================================*/
#include "tree.h"

int main(int argc, char *argv[])
{ 
    Ptree root;
    root = init(1,9);
    printf("-----先序遍历-----\n");
    preorder(root);
    puts("");
    printf("-----中序遍历-----\n");
    inorder(root);
    puts("");
    printf("-----后序遍历-----\n");
    postorder(root);
    puts("");


    return 0;
} 

结果

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值