首页 > 代码库 > 二叉树排序
二叉树排序
二叉树排序
// 二叉树排序.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);
}
}
二叉树排序
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。