二叉树排序
来源:互联网 发布:lurker间谍软件多少钱 编辑:程序博客网 时间:2024/05/14 11:48
#include <stdio.h>#include <malloc.h>#include <memory.h>typedef struct node{ int v; struct node * lchild; struct node * rchild;}TREE_NODE_S;void insert_node(TREE_NODE_S * p, TREE_NODE_S *node){ if(p->v > node->v) { if(NULL == p->lchild) { p->lchild = node; return; } else return insert_node(p->lchild, node); } else { if(NULL == p->rchild) { p->rchild = node; return; } else { return insert_node(p->rchild, node); } }}TREE_NODE_S *create_sort_tree(int *a, int num){ int i; TREE_NODE_S *p, *t; p = (TREE_NODE_S *)malloc(sizeof(TREE_NODE_S)); if(NULL == p) { return NULL; } memset(p, 0, sizeof(TREE_NODE_S)); p->v = *a; for(i = 1; i < num; i++) { TREE_NODE_S *t1 = (TREE_NODE_S*)malloc(sizeof(TREE_NODE_S)); if(NULL == t1) { return NULL; } memset(t1, 0, sizeof(TREE_NODE_S)); t1->v = *(a + i); insert_node(p, t1);/* t = p; while(t) { if(t->v > *(a + i)) { printf("l:%d ", t->v); if(NULL == t->lchild) { t->lchild = t1; break; } else { t = t->lchild; } } else { printf("r:%d ", t->v); if(NULL == t->rchild) { t->rchild = t1; break; } else { t = t->rchild; } } } printf("\n");*/ } return p;}int btree_depth(TREE_NODE_S *p){ int i,j; if(NULL == p) return -1; i = btree_depth(p->rchild); j = btree_depth(p->lchild); if(i > j) return i + 1; else return j + 1;}void travel(TREE_NODE_S * p){ if(NULL == p) return; travel(p->lchild); printf("%d ", p->v); travel(p->rchild);}int main(){ TREE_NODE_S *p; int depth; int a[] = {1,22,3,54,234,22,34}; p = create_sort_tree(a, 7); depth = btree_depth(p); printf("depth:%d\n", depth); travel(p); printf("\n"); }