现在的位置: 首页 > 综合 > 正文

一个简单的二叉树排序算法

2012年01月02日 ⁄ 综合 ⁄ 共 1721字 ⁄ 字号 评论关闭

  今天上班时没给安排任务,我拿起了数据结构看了会,感觉非常好。之前也看过,但是看不下去,很难懂。大四自学了一年java,毕业后又用c++一年了,就算这半年写的代码比较多,可能之前用java和vc++都是在使用类库了,这半年有了一个代码量的积累了,自我感觉还是比以前提高了不少。当然在大家看来还是非常菜的。下午看了会二叉树,之前对二叉树就了解过一点,心想先不看书,先整一个出来再去看书,那样更容易看懂书。不知大家有没有过这种体会,有些代码自己看觉得挺头疼,但是当你写过一个类似的,或者干脆让你来实现 这个程序,你写过重点是你动脑思考过后,再去看别人写过的同样的功能的代码,也可以很快理解。

不啰嗦了。我们公司有个项目经理说,菜鸟一般都是把写的代码贴出来,牛人都是总结出些高论,我现在能且仅能是菜鸟了,哈。

/**
功能:实现 二叉树排序。
简单作为示例,方法也是采用的我直接可以想到的,比较直观。
*/
#include
<stdlib.h>
#include
<stdio.h>
#include
<string.h>


//二叉树中 结点 结构
struct BinaryTree{
int number;
struct BinaryTree* left;
struct BinaryTree* right;
};

//打印数组。我每次写关于数组的算法时都会写一个这种函数,供观察使用。
int print_arr(int *p, int n)
{
if(0 == p || 0 == n)
{
printf(
"Array is null!");
return -1;
}
int i = 0;
for(; i<n; i++)
{
printf(
"%3d ", p[i]);
if(i%10 == 9)
{
printf(
"\n");
}
}
if(i%10 != 9)
{
printf(
"\n");
}
return 0;

}

//打印二叉树。当往二叉树填充数据后,按照中序遍历,也就是可以按升序显示出来。
void print_binarytree(struct BinaryTree* bt)
{
if(bt == 0)
{
return ;
}
//
if(bt->left != 0)
{
print_binarytree(bt
->left);
}
//
printf("%3d ",bt->number);
//
if(bt->right != 0)
{
print_binarytree(bt
->right);
}
return ;
}

//将数组填充到二叉树里边去。
int array_to_binarytree(int *p, int n, struct BinaryTree* root)
{
if(0 == p || n == 0)
{
printf(
"Array is null!\n");
return -1;
}

root
->number = p[0];
root
->left = 0;
root
->right = 0;

struct BinaryTree *temp = 0;

for(int i=1; i<n; i++)
{
temp
= root;
struct BinaryTree* t = (struct BinaryTree*)malloc(sizeof(struct BinaryTree));
t
->number = p[i];
t
->left = 0;
t
->right = 0;
while(temp != 0)
{
if(t->number > temp->number)
{
if(temp->right == 0)
{
temp
->right = t;
break;
}
else
{
temp
= temp->right;
}
}
else
{
if(temp->left == 0)
{
temp
->left = t;
break;
}
else
{
temp
= temp->left;
}
}
}
}

return 0;
}



int main()
{
int a[5] = {3,5,1,8,4};
print_arr(a,
5);

//根节点,并为根节点开辟空间
struct BinaryTree* root=(struct BinaryTree*)malloc(sizeof(struct BinaryTree));
//将数组中的元素填充到二叉树中去。
array_to_binarytree(a,5,root);
//打印二叉树
print_binarytree(root);
free(root);

puts(
"");
return 0;
}

抱歉!评论已关闭.