随机生成10个[0, 100].上的随机数,使用二叉树对
其进行从小到大的排序,并输出排序后的结果。
#include#include typedef struct Tree { int data; struct Tree* lt; struct Tree* rt; }tree; tree* creattree(tree* root, int data) { if (root == NULL) { tree* newnode = (tree*)malloc(sizeof(tree)); newnode->data = data; newnode->lt = NULL; newnode->rt = NULL; return newnode; } if (data < root->data) root->lt = creattree(root->lt, data); else root->rt = creattree(root->rt, data); return root; } void printfinord(tree* root) { if (root->lt) { printfinord(root->lt); } printf("%d ", root->data); if (root->rt) { printfinord(root->rt); } } int main() { tree* root = NULL; int a[10]; for (int i = 0; i < 10; i++) { a[i] = rand() % 101; root = creattree(root, a[i]); printf("%d ", a[i]); } printf("n"); printfinord(root); }
从控制台输入任意一组数字,以此在内存中重构一棵完全二叉树。
要求:每输入一个数字,立刻生成对应的二叉树并在控制台输出此二叉树。
#include#include #include typedef struct Tree { char data[10]; struct Tree* lt; struct Tree* rt; }tree; typedef struct Que { struct Tree* t[100]; int pre; int lat; }que; void creattree(tree** root, que** list, char* data) { tree* newnode = (tree*)malloc(sizeof(tree)); strcpy(newnode->data, data); newnode->lt = NULL; newnode->rt = NULL; if ((*list)->pre == (*list)->lat) { (*list)->pre = ((*list)->pre + 1) % 100; (*list)->t[(*list)->pre] = newnode; *root = newnode; } else if ((*list)->t[((*list)->lat + 1) % 100]->lt == NULL) { (*list)->t[((*list)->lat + 1) % 100]->lt = newnode; (*list)->pre = ((*list)->pre + 1) % 100; (*list)->t[(*list)->pre] = newnode; } else { (*list)->t[((*list)->lat + 1) % 100]->rt = newnode; (*list)->lat = ((*list)->lat + 1) % 100; (*list)->pre = ((*list)->pre + 1) % 100; (*list)->t[(*list)->pre] = newnode; } } void printfnode(char* data, char c, int depth) { for (int i = 0; i < depth; i++) printf(" "); printf("%c %sn", c, data); } void printftree(tree* root, char c, int depth) { if (root == NULL) { printfnode("*", c, depth); return; } if (root->lt == NULL && root->rt == NULL) { printfnode(root->data, c, depth); return; } printftree(root->rt, '/', depth + 1); printfnode(root->data, c, depth); printftree(root->lt, '\', depth + 1); } int main() { tree* root = (tree*)malloc(sizeof(tree)); que* list = (que*)malloc(sizeof(que*)); char str[10]; list->pre = 0; list->lat = 0; gets(str); while (*str != '*') { creattree(&root, &list, str); printftree(root, ' ', 0); printf("--------------------------------------------------------------n"); gets(str); } return 0; }



