数据结构—二叉排序树
原理:参考趣学数据结构
代码:
# include <stdio.h>
# include <stdlib.h>
typedef struct bstTree { int data; struct bstTree * lchild, * rchild;
} bstTree;
void createBSTTree ( bstTree* & T, int data) { bstTree * p = NULL ; if ( ! T) { p = ( bstTree* ) malloc ( sizeof ( bstTree) ) ; p-> data = data; p-> lchild = p-> rchild = NULL ; T = p; return ; } if ( data < T-> data) { createBSTTree ( T-> lchild, data) ; } else { createBSTTree ( T-> rchild, data) ; }
}
void prePrint ( bstTree* & BSTTree) { if ( BSTTree) { printf ( "%d " , BSTTree-> data) ; prePrint ( BSTTree-> lchild) ; prePrint ( BSTTree-> rchild) ; }
}
int main ( ) { bstTree* T= NULL ; int count, data; printf ( "开始构造二叉排序树:\n输入二叉排序树结点的数目:" ) ; scanf_s ( "%d" , & count) ; while ( count-- ) { printf ( "输入二叉排序树的第%d个结点:" , count+ 1 ) ; scanf_s ( "%d" , & data) ; createBSTTree ( T, data) ; } printf ( "前序遍历二叉排序树\n" ) ; prePrint ( T) ; printf ( "\n" ) ; system ( "pause" ) ; return 0 ;
}
测试截图:
时间复杂度O(nlogn),空间复杂度O(1)
如果存在什么问题,欢迎批评指正!谢谢