C、C++二叉树简单构建和顺序存储

1 篇文章 0 订阅
0 篇文章 0 订阅
完全二叉树、满二叉树既可以用链式存储,也可以用数组来顺序存储。但是它们在在效率上却有着很大差别:
顺序存储:
    优点:可以相对密集的存储树的结点,主要是通过k的计算公式。
    缺点:可以存储一般二叉树但是存储效率不高,不能用于一般树。
        构建树时必须先知道待构建树的高度。
链式存储:
    优点:构建时不必先知道树的高度。

可表示一般二叉树。

include

include

include

define T int

define Length 7 //(pow(2,3)-1)=>数组长度 3为树深度

typedef struct
{
T data[Length];
}Tree;
//index根节点从 1开始
void CreateTree(Tree &tree,int k){
T temp;
scanf(“%d”,&temp);
if (temp==-1)
{
return;
}
tree.data[k-1]=temp;

if(2*k<=Length){
    printf("intput the left_child of %d (-1 end) \n",temp );
    CreateTree(tree,2*k);
}else{
    return ;
}


 if(2*k+1<=Length){
    printf("intput the right_child of %d (-1 end)\n", temp);
    CreateTree(tree,2*k+1);
}

}

void PreOrder(Tree &tree,int k){
printf(“%d\t”,tree.data[k] );
if (2*k<=Length )
{
/* code */
}
}

int main(int argc, char const *argv[])
{
Tree tree;
printf(“%s\n”,”input the value of root” );
CreateTree(tree,1);
for (int i = 0; i < Length; ++i)
{
printf(“%d\t”,tree.data[i] );
}
return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值