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

完全二叉树、满二叉树既可以用链式存储,也可以用数组来顺序存储。但是它们在在效率上却有着很大差别:
顺序存储:
    优点:可以相对密集的存储树的结点,主要是通过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;
}

猜你喜欢

转载自blog.csdn.net/qq_29012499/article/details/82086042