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

xiaoxiao2021-02-28  77

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

#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+1 CreatTree(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; }

转载请注明原文地址: https://www.6miu.com/read-81452.html

最新回复(0)