二叉树排序

二叉树排序

// 二叉树排序.cpp : 定义控制台应用程序的入口点。

// #include "stdafx.h" #include<stdio.h> #include<stdlib.h> #include<windows.h> struct data{ int num; struct data* lbaby, *rbaby; }*root, *tree, *leaf; void find(int,struct data*); void output(struct data*); void main() { int data[10] = {75,23,98,44,57,12,29,64,38,82}; int i; printf("\n<<Binary tree sort>>\n"); printf("\nNumber:"); for (i = 0; i < 10; i++) printf("%d ",data[i]); puts(""); for (i = 0; i < 60; i++) printf("-"); root = (struct data*)malloc(sizeof(struct data)); root->num = data[0]; //建立树根 root->lbaby = NULL; root->rbaby = NULL; printf("\nAccess:"); output(root); leaf = (struct data*)malloc(sizeof(struct data)); for (i = 1; i < 10; i++) //建立树枝 { leaf->num = data[i]; leaf->lbaby = NULL; leaf->rbaby = NULL; find(leaf->num,root); if (leaf->num>tree->num)//假设比父节点大,则放右子树 tree->rbaby = leaf; else //否则放在左子树 tree->lbaby = leaf; printf("\nAccess:"); output(root); leaf = (struct data*)malloc(sizeof(struct data)); } puts(""); for (i = 0; i < 60; i++) printf("-"); printf("\nSorting:"); output(root); printf("\n"); system("pause"); } /*寻找新节点存放的位置*/ void find(int input, struct data* papa) { if ((input>papa->num) && (papa->rbaby != NULL)) find(input, papa->rbaby); else if ((input < papa->num) && (papa->lbaby != NULL)) find(input, papa->lbaby); else tree = papa; } /*输出数据*/ void output(struct data* node) { if (node != NULL) { output(node->lbaby); printf("%d ",node->num); output(node->rbaby); } }

測试1:

posted @ 2017-08-03 19:40  lytwajue  阅读(229)  评论(0编辑  收藏  举报