数组转二叉树

全部代码

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <assert.h>
 4 
 5 typedef struct node
 6 {
 7     int nValue;
 8     struct node *pLeft;
 9     struct node *pRight;
10 }BiTree;
11 
12 BiTree *ArrToBiTree(int arr[], int len)
13 {
14     BiTree *pRoot = NULL;
15     int i;
16 
17     assert(arr!=NULL && len>0);
18 
19     //创建结构体数组
20     pRoot = (BiTree *)malloc(sizeof(BiTree)*len);
21     if(NULL == pRoot)
22     {
23         printf("pRoot空间分配失败!\n");
24         exit(-1);
25     }
26     
27     //结构体数组赋初值
28     for(i=0; i<len; ++i)
29     {
30         pRoot[i].nValue = arr[i];
31         pRoot[i].pLeft = NULL;
32         pRoot[i].pRight = NULL;
33     }
34 
35     //父亲节点与左右孩子关联
36     for(i=0; i<=len/2-1; ++i)
37     {
38         //有左孩子
39         if(2*i+1 < len)
40         {
41             pRoot[i].pLeft = &pRoot[2*i+1];
42         }
43 
44         //有右孩子
45         if(2*i+2 < len) 
46         {
47             pRoot[i].pRight = &pRoot[2*i+2];
48         }
49     }
50 
51     return pRoot;
52 }
53 
54 void PrevOrderTraversal(BiTree *pRoot)
55 {
56     if(NULL == pRoot)
57     {
58         return;
59     }
60 
61     printf("%d ", pRoot->nValue);
62     PrevOrderTraversal(pRoot->pLeft);
63     PrevOrderTraversal(pRoot->pRight);
64 }
65 
66 int main(void)
67 {
68     BiTree * pRoot = NULL;
69 
70     int arr[] = {1, 2, 3, 4, 5, 6, 7};
71     int len = sizeof(arr)/sizeof(arr[0]);
72     pRoot = ArrToBiTree(arr, len);
73     PrevOrderTraversal(pRoot);
74 
75     return 0;
76 }

 

转载于:https://www.cnblogs.com/chen-cai/p/7811182.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值