线索二叉树小例
来源:互联网 发布:淘宝怎么提醒买家收货 编辑:程序博客网 时间:2024/05/13 09:20
二叉树在c语言中的重要性不需再说,而线索二叉树则是二叉树中比较重要的一个应用。
一般的二叉树存储模式,空链的数目非常多,线索二叉树则利用这些空链使其指向节点的前驱和后继,改善二叉树的遍历效率。这些被重新利用的空链也就是“线索”了。
中序遍历线索二叉树:
#include <stdio.h>#include <stdlib.h>#define FALSE 0 /* point is not thread */#define TRUE 1 /* point is thread */typedef struct threaded_tree *threaded_pointer;typedef struct threaded_tree{ short int left_thread; threaded_pointer left_child; char data; threaded_pointer right_child; short int right_thread;}threaded_tree;threaded_pointer pre;threaded_pointer createTp(threaded_pointer T){/* create a binarytree */ char ch; scanf("%c", &ch); if(ch == '#') return NULL; T = (threaded_pointer)malloc(sizeof(threaded_tree)); T->data = ch; T->left_thread = FALSE; T->right_thread = FALSE; T->left_child = createTp(T->left_child); T->right_child = createTp(T->right_child); return T;}void inorderthread(threaded_pointer *p, threaded_pointer T){/* add a root node to tree and thread tree */ (*p) = (threaded_pointer)malloc(sizeof(threaded_tree)); (*p)->left_thread = FALSE; (*p)->right_thread = FALSE; (*p)->right_child = (*p); if(!T){ (*p)->left_child = p; } else{ (*p)->left_child = T; pre = (*p); in_thread(T); pre->right_thread = TRUE; pre->right_child = (*p); }}void in_thread(threaded_pointer T){/* inorder thread tree */ if(T){ in_thread(T->left_child); if(!T->left_child){ T->left_thread = TRUE; T->left_child = pre; } if(!pre->right_child){ pre->right_thread = TRUE; pre->right_child = T; } pre = T; in_thread(T->right_child); }}/* these two functions can be finded in the book : fundamentals of data structures in C */threaded_pointer insucc(threaded_pointer tree){/* find the inorder sucessor of tree in a threaded binary tree */ threaded_pointer temp; temp = tree->right_child; if(!tree->right_thread) while(!temp->left_thread) temp = temp->left_child; return temp;}void tinorder(threaded_pointer tree){/* traverse the threaded binary tree inorder */ threaded_pointer temp = tree; for(;;){ temp = insucc(temp); if(temp == tree) break; printf("%3c", temp->data); } printf("\n");}int main(){ threaded_pointer p, threadTree; printf("input the binary tree (# == NULL):"); threadTree = createTp(threadTree); inorderthread(&p, threadTree); printf("the threaded binary tree: "); tinorder(p); return 0;}
程序结果:
0 0
- 线索二叉树小例
- 线索二叉树算法
- C#线索二叉树
- 线索二叉树
- C#线索二叉树
- 线索二叉树
- 线索二叉树
- 线索化二叉树
- 线索二叉树
- C#线索二叉树
- C#线索二叉树
- 给二叉树加中序线索
- 线索二叉树
- 线索二叉树实例
- 线索二叉树
- 线索二叉树算法
- C++线索二叉树
- 线索二叉树
- python3自动登录
- 一个能让cin和scanf 一样快的方法:
- C语言 实现两个数组内容交换
- 'XCTest/XCTest.h' file not found
- java/对象数组/集合
- 线索二叉树小例
- hiho一下第一周
- java简单排序-插入排序
- Maven相关元素汇总
- 图算法2之1003
- head first java 读书笔记
- scikit-learn : LASSO
- Problem4-1019
- Largest Divisible Subset