欢迎来到代码驿站!

C代码

当前位置:首页 > 软件编程 > C代码

C语言递归实现线索二叉树

时间:2021-10-24 10:33:36|栏目:C代码|点击:

本文实例为大家分享了C语言递归实现线索二叉树的具体代码,供大家参考,具体内容如下

描述:将二叉树中结点的空左孩子指针域指向前驱结点,将空的右孩子指针域指向后继结点。

code:

#pragma warning(disable:4996)
#include<stdio.h>
#include<stdlib.h>
typedef struct TreeNode {
 char data;
 struct TreeNode *lchild, *rchild;
 int ltag, rtag;
}Tree,*BTree;
BTree Build_Tree(void) {
 BTree T;
 char ch;
 scanf("%c", &ch);
 if (ch == '#') {
 T = NULL;
 }
 else {
 T = (BTree)malloc(sizeof(Tree));
 T->data = ch;
 T->ltag = 0;
 T->rtag = 0;
 T->lchild = Build_Tree();
 T->rchild = Build_Tree();
 }
 return T;
}
//先序线索化
void Pre_Thread(BTree cur, BTree *pre) {
 if (cur && cur->ltag==0) {
 printf("%c ", cur->data);
 if (cur->lchild == NULL) {
  cur->lchild = *pre;
  (*pre)->ltag = 1;
  cur->ltag = 1;
 }
 if (cur->rchild == NULL) {
  cur->rtag = 1;
 }
 if (*pre && (*pre)->rtag == 1) {
  (*pre)->rchild = cur;
 }
 *pre = cur;
 Pre_Thread(cur->lchild, pre);
 Pre_Thread(cur->rchild, pre);
 }
}
//中序线索化
void In_Thread(BTree cur, BTree *pre) {
 if (cur) {
 In_Thread(cur->lchild, pre);
 printf("%c ", cur->data);
 if (cur->lchild==NULL) {
  cur->lchild = *pre;
  cur->ltag = 1;
 }
 if (cur->rtag == NULL) {
  cur->rtag = 1;
 }
 if (*pre && (*pre)->rtag == 1) {
  (*pre)->rchild = cur;
 }
 *pre = cur;
 In_Thread(cur->rchild, pre);
 }
}
//后序线索化
void Post_Thread(BTree cur, BTree *pre) {
 if (cur) {
 Post_Thread(cur->lchild, pre);
 Post_Thread(cur->rchild, pre);
 printf("%c ", cur->data);
 if (cur->lchild == NULL) {
  cur->lchild = *pre;
  cur->ltag = 1;
 }
 if (cur->rchild == NULL) {
  cur->rtag = 1;
 }
 if (*pre && (*pre)->rtag == 1) {
  (*pre)->rchild = cur;
 }
 *pre = cur;
 }
}
int main(void) {
 BTree T,p=NULL;
 T = Build_Tree();
 Pre_Thread(T, &p);
 //In_Thread(T, &p);
 //Post_Thread(T, &p);
 return 0;
}

跑时分别运行前序、中序、后序线索化。

上一篇:C++调用tensorflow教程

栏    目:C代码

下一篇:C语言冒泡排序法心得

本文标题:C语言递归实现线索二叉树

本文地址:http://www.codeinn.net/misctech/181067.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有