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

今天上班时没给安排任务,我拿起了数据结构看了会,感觉非常好。之前也看过,但是看不下去,很难懂。大四自学了一年java,毕业后又用c++一年了,就算这半年写的代码比较多,可能之前用java和vc++都是在使用类库了,这半年有了一个代码量的积累了,自我感觉还是比以前提高了不少。当然在大家看来还是非常菜的。下午看了会二叉树,之前对二叉树就了解过一点,心想先不看书,先整一个出来再去看书,那样更容易看懂书。不知大家有没有过这种体会,有些代码自己看觉得挺头疼,但是当你写过一个类似的,或者干脆让你来实现 这个程序,你写过重点是你动脑思考过后,再去看别人写过的同样的功能的代码,也可以很快理解。
不啰嗦了。我们公司有个项目经理说,菜鸟一般都是把写的代码贴出来,牛人都是总结出些高论,我现在能且仅能是菜鸟了,哈。
/** 功能:实现 二叉树排序。 简单作为示例,方法也是采用的我直接可以想到的,比较直观。 */ #include #include #include //二叉树中 结点 结构 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(; ileft != 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; inumber = 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; }
Tags: 

延伸阅读

最新评论

发表评论