#include "stdio.h" #include "stdlib.h" #include "string.h" #include "queue.h" void arraytotree(int *a, int len, struct student **p) { if(len) { *p = (struct student*)malloc(sizeof(struct student)); (*p)->value = a[len/2]; arraytotree(a, len/2, &((*p)->lchild)); arraytotree(a+len/2+1, len-len/2-1, &((*p)->rchild)); } else { *p = NULL; } } void display_tree(struct student *head) { if(head->lchild)display_tree(head->lchild); printf("%d\t", head->value); if(head->rchild)display_tree(head->rchild); } void display_tree_layer(struct student *head) { Queue *queue = new Queue; printf("%d\t", head->value); if(head->lchild)queue->enqueue(head->lchild); if(head->rchild)queue->enqueue(head->rchild); while(!queue->empty()) { struct student *p = queue->dequeue(); printf("%d\t", p->value); if(p->lchild)queue->enqueue(p->lchild); if(p->rchild)queue->enqueue(p->rchild); } } int main() { int a[] = {1,2,3,4,5,6,7,8,9,10}; struct student *tree; arraytotree(a, sizeof(a)/sizeof(a[0]), &tree); printf("After convert:\n"); display_tree(tree); printf("\nlay order :\n"); display_tree_layer(tree); printf("\n"); return 0; }
|