用数组中序遍历二叉树c语言,从前序遍历数组创建二叉树 c实现

网上很多实现创建二叉树的方法,很大程度受《大话数据结构》影响,不断通过输入节点来创建。个人觉得这样很不方便,修改起来也很麻烦。不过按照《大话数据结构》创建二叉树的思路,可以从前序遍历的数组创建二叉树,首先,规定该数组的格式:

格式还是按照《大话数据结构》里面,最后的空节点用一个特殊的值来替代,并且也遍历进数组

9b5601ba136e09baf6555e90df1750d4.png

其中ABCD就是自己的数,#可以用以数来表示。这里我用0x7fffffff来表示。具体的数值,应该根据自己项目情况,选取不会出现的数值来替代。

#include

#include

#define MAXNUM 0x7fffffff

struct BiTreeNode {                                                //定义树节点

int dat;

struct BiTreeNode *lchild;                                    //左子树指针

struct BiTreeNode *rchild;                                    //右子树指针

};

/*

将二叉树的前序遍历存入数组,末尾空位置放置0x7fffffff

*/

void creatBiTree(struct BiTreeNode** head, int a[], int length, int index) {

static int count;

count = index;

if (count >= length) {

return;

}

if (length <= 0 || a[count] == MAXNUM) {

*head = NULL;

return;

}

(*head) = (struct BiTreeNode *)malloc(sizeof(struct BiTreeNode));

(*head)->dat = a[count];

creatBiTree(&((*head)->lchild), a, length, count + 1);

creatBiTree(&((*head)->rchild), a, length, count + 1);

}

void preOrdV(struct BiTreeNode *head) {                                //二叉树的前序遍历

if (head == NULL) {

return;

}

printf("%d ", head->dat);

preOrdV(head->lchild);

preOrdV(head->rchild);

}

void inOrdV(struct BiTreeNode *head) {                            //二叉树中序遍历

if (head == NULL) {

return;

}

inOrdV(head->lchild);

printf("%d ", head->dat);

inOrdV(head->rchild);

}

void postOrdV(struct BiTreeNode *head) {                        //后续遍历二叉树

if (head == NULL) {

return;

}

postOrdV(head->lchild);

postOrdV(head->rchild);

printf("%d ", head->dat);

}

int main() {

struct BiTreeNode* head = NULL;

int TreeNum[] = { 1, 2, 4, MAXNUM , 7, MAXNUM, MAXNUM, MAXNUM, 3, 5, MAXNUM, MAXNUM, 6, 8, MAXNUM, MAXNUM, MAXNUM };

creatBiTree(&head, TreeNum, sizeof(TreeNum) / sizeof(int), 0);

preOrdV(head);

printf("\n");

inOrdV(head);

printf("\n");

return 0;

}

我们来验证一下:

de29a33487b1851330592a95369ea660.png

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值