69,373
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<stdlib.h>
typedef int Element;
struct BNode{
struct BNode *leftChild;
struct BNode *rightChild;
Element e;
};
typedef BNode * Node;
struct BTree
{
//带头结点的树
Node first;
int count;
};
typedef BTree * Tree;
BTree *CreateBTree()
{
Tree t=(Tree)malloc(sizeof(struct BTree));
t->first=(Node)malloc(sizeof(struct BNode));
t->count=0;
return t;
}
//递归遍历
void copyBT(Tree T,int A[],int n,int i,Node p)
{
// i>n-1返回
if(i>n-1) return ;
if(A[i]!=0)
{
Node newNode =(Node)malloc(sizeof(struct BNode));
newNode->e=A[i];
// 左孩子
if(i%2==0)
p->leftChild=newNode;
else/*右孩子*/
p->rightChild=newNode;
p=newNode;
T->count++;
copyBT(T,A,n,2*i,p);
copyBT(T,A,n,2*i+1,p);
}
}
int main()
{
Tree t=CreateBTree();
//指向父节点
Node p=t->first;
int A[8]={0,1,2,3,4,5,6,7};
//数组我们从1开始。第一个默认为0。便于2*i和2*i+1操作
copyBT(t,A,8,1,p);
return 0;
}