The C language recursively implements the clue binary tree

  • 2020-05-30 20:54:02
  • OfStack

The example of this paper is to share the specific code of C language recursive implementation clue 2 fork tree for your reference, the specific content is as follows

Description: point the null left child pointer field of the node in the 2 fork tree to the precursor node, and point the null right child pointer field to the successor node.

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;
}
// Order the clues first 
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);
 }
}
// Medium order clew 
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);
 }
}
// Post-order clew 
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;
}

When running, running preorder, in order, after the sequence of clues.


Related articles: