• 数组转二叉树


    全部代码

     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空间分配失败!
    ");
    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 }
  • 相关阅读:
    c/c++字符串传递
    从一个小程序明白new和delete的奇特现象
    Linux下构造函数string需要注意的问题
    字符串转time_t
    CentOS7基础建站指南(笔记)
    图与搜索
    面向的对象编程的小猫腻
    多线程编程
    生产者消费者模式-Java实现
    Java-代理模式的理解
  • 原文地址:https://www.cnblogs.com/chen-cai/p/7811182.html
Copyright © 2020-2023  润新知