数据结构第六章-二叉树顺序存储变链式存储

来源:互联网 发布:linux启动网卡1的命令 编辑:程序博客网 时间:2024/06/05 19:12

给你一个顺序存储的,按照它新建一个链式存储的数


#include<stdio.h>#include<iostream>#include<stdlib.h>using namespace std;int a[100];int n;typedef struct Node{int data;struct Node *lchild;struct Node *rchild;}BiTNode, *BiTree;void CreatTree(int a[], BiTree *root, int i){if (a[i] == -1 || i>n)//之前写成&&就建立不了 两种情况都要退出*root = NULL;else{*root = (BiTree)malloc(sizeof(BiTNode));(*root)->data = a[i];CreatTree(a, &((*root)->lchild), 2 * i);//1开始的左子树是2*i,右子树是2*i+1CreatTree(a, &((*root)->rchild), 2 * i + 1);//0开始的左子树是2*i+1,右子树是2*i+2}}void inorder(BiTree root){if (root){inorder(root->lchild);printf("%d ", root->data);inorder(root->rchild);}}int main(){scanf("%d", &n);for (int i = 1; i <= n; i++){scanf("%d", &a[i]);}BiTNode *root;CreatTree(a, &root, 1);inorder(root);cout << endl;}


0 0