#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef struct Node {
int key;
int ltag, rtag;//tag=1时建立线索,tag=0时为原遍历
struct Node* lchild, * rchild;
}Node;
Node* getNewNode(int key) {
Node *p = (Node*)malloc(sizeof(Node));
p->key = key;
p->lchild = p->rchild = NULL;
p->ltag =p-> rtag = 0;
return p;
}
Node* insert(int key, Node* root) {
if (root == NULL)return getNewNode(key);
if (rand() % 2)root->lchild = insert(key, root->lchild);
else root->rchild = insert(key, root->rchild);
return root;
}
void pre_order(Node* root) {
if (root == NULL)return;
printf("%3d", root->key);
if(root->ltag==0) pre_order(root->lchild);
if (root->rtag == 0) pre_order(root->rchild);
return;
}
void in_order(Node* root) {
if (root == NULL)return;
if (root->ltag == 0)in_order(root->lchild);
printf("%3d", root->key);
if (root->rtag == 0)in_order(root->rchild);
return;
}
void post_order(Node* root) {
if (root == NULL)return;
if (root->ltag == 0)post_order(root->lchild);
if (root->rtag == 0)post_order(root->rchild);
printf("%3d", root->key);
return;
}
Node* pre_Node = NULL;
Node *inorder_root = NULL;
void __build_inorder_thread(Node* root) {
if (root == NULL)return;
if (root->ltag == 0)__build_inorder_thread(root->lchild);
if (inorder_root == NULL)inorder_root = root;
if (root->lchild == NULL) {
root->lchild == pre_Node;
root->ltag = 1;
}
if (pre_Node && pre_Node->rchild == NULL) {
pre_Node->rchild = root;
pre_Node->rtag = 1;
}
pre_Node = root;
if (root->rtag == 0)__build_inorder_thread(root->rchild);
return;
}
void build_inorder_thread(Node* root) {
__build_inorder_thread(root);
pre_Node->rchild = NULL;
pre_Node->rtag = 1;
return;
}
void clear(Node* root) {
if (root == NULL)return;
clear(root->lchild);
clear(root->rchild);
free(root);
return;
}
Node* getNext(Node* root) {
if (root->rtag == 1)return root->rchild;
root = root->rchild;
while (root->ltag == 0 && root->lchild)root = root->lchild;
return root;
}
int main() {
srand(time(0));
Node* root = NULL;
for (int i=0; i < MAX_OP; i++) {
root = insert(rand() % 100, root);
}
pre_Node = inorder_root = NULL;
pre_Node = NULL;
__build_inorder_thread(root);
pre_order(root); printf("\n");
in_order(root); printf("\n");
post_order(root); printf("\n");
Node* node = inorder_root;
while (node) {
printf("%3d", node->key);
node = getNext(node);
}
printf("\n");
clear(root);
return 0;
}
二叉树线索化
最新推荐文章于 2024-09-08 17:41:31 发布