数据结构—二叉线索树
原理:参考趣学数据结构
代码:
# include <stdio.h>
# include <stdlib.h>
typedef struct bmTree { int data; struct bmTree * lchild, * rchild; int ltag, rtag;
} bmTree;
bmTree * pre= NULL ;
void createBTree ( bmTree* & BMTree) { int data; scanf_s ( "%d" , & data) ; if ( data == - 1 ) { BMTree = NULL ; } else { BMTree= ( bmTree* ) malloc ( sizeof ( bmTree) ) ; BMTree-> data = data; createBTree ( BMTree-> lchild) ; createBTree ( BMTree-> rchild) ; } }
void midTraverseBMTree ( bmTree* & BMTree) { bmTree* T = BMTree; if ( T) { midTraverseBMTree ( T-> lchild) ; if ( ! T-> lchild) { T-> ltag = 1 ; T-> lchild = pre; } else { T-> ltag = 0 ; } if ( pre) { if ( ! pre-> rchild) { pre-> rtag = 1 ; pre-> rchild = T; } else { pre-> rtag = 0 ; } } pre = T; midTraverseBMTree ( T-> rchild) ; }
}
void printMideBMT ( bmTree * T) { bmTree * p = T; while ( p) { while ( p-> ltag== 0 ) { p = p-> lchild; } printf ( "%d " , p-> data) ; while ( p-> rtag == 1 && p-> rchild) { p = p-> rchild; printf ( "%d " , p-> data) ; } p = p-> rchild; }
}
int main ( ) { bmTree* T; createBTree ( T) ; midTraverseBMTree ( T) ; pre-> rchild = NULL ; pre-> rtag = 1 ; printf ( "二叉线索树进行中序遍历:" ) ; printMideBMT ( T) ; printf ( "\n" ) ; system ( "pause" ) ; return 0 ;
}
测试截图:
时间复杂度O(nlogn),空间复杂度O(1)
如果存在什么问题,欢迎批评指正!谢谢!