将一个数组转换成深度最低的二叉树
2012-05-29 17:38
288 查看
问题定义:
Givena sorted(increasing order) array, write an algorithm to create abinary tree with minimal height.
思路:
这题还是比较简单的,从已排序的数组和高度最低的二叉树这两个关键词中就可以得到一些启发,类似与二分查找,将最中间的元素作为根节点,左边的元素插入到左子树,右边的元素插入到右子树即可,最后实现了一个二叉查找树。
代码如下:
Givena sorted(increasing order) array, write an algorithm to create abinary tree with minimal height.
思路:
这题还是比较简单的,从已排序的数组和高度最低的二叉树这两个关键词中就可以得到一些启发,类似与二分查找,将最中间的元素作为根节点,左边的元素插入到左子树,右边的元素插入到右子树即可,最后实现了一个二叉查找树。
代码如下:
#include <algorithm> #include <stdio.h> #include <time.h> struct node { int data; struct node * lchild; struct node * rchild; }; //将数组转换为深度最低的二叉树,采用了二分查找的思想 struct node* ConvertArrayToTree(int data[], int first, int last) { if (last < first) { return NULL; } else { int mid = ( last + first ) / 2; struct node * newNode = NULL; newNode = (struct node *)malloc(sizeof(struct node)); newNode->data = data[mid]; newNode->lchild = ConvertArrayToTree(data, first, mid - 1); newNode->rchild = ConvertArrayToTree(data, mid + 1, last); return newNode; } } //中序遍历 void Traverse(struct node *root) { if (root == NULL) { return; } Traverse(root->lchild); printf("%d\t", root->data); Traverse(root->rchild); } int main(int argc, char* argv[]) { const int SIZE = 100; int data[SIZE]; int i, j; int flag = 1; struct node *head = NULL; srand(time(0)); for (i = 0; i < SIZE; i++) { data[i] = rand() % SIZE; flag *= -1; data[i] *= flag; } std::sort(data, data + SIZE); for (i = 0; i < SIZE; i++) { printf("%d\t", data[i]); } printf("\n"); head = ConvertArrayToTree(data, 0, SIZE - 1); Traverse(head); printf("\n"); return 0; }
相关文章推荐
- 将一个数组转换成深度最低的二叉树
- 把一个二叉树转换成一棵最右深度树,并且保证前序遍历顺序不变
- android 将图片内容解析成字节数组,将字节数组转换为ImageView可调用的Bitmap对象,图片缩放,把字节数组保存为一个文件,把Bitmap转Byte
- 怎样把C语言数组中存放的四个十六进制数合并成一个十六进制数,并转换成十进制?
- 随机生成一个三维数组,编程求深度的平均值,保存在一个二维数组中。
- 通过二叉树形式给一个数组排序
- 在C#中将任意数值类型数据与字节数组相互转换的一个方法
- 3.有一个整数数组,请声明一个字符串数组,将整数数组中的每一个元素的值转换为字符串保存到字符串数组中
- 把一个有序整数数组放到二叉树
- 怎样编写一个程序,把一个有序整数数组放到二叉树中?
- 把函数参数转换到一个数组中
- 数组转换list的一个方法
- android 将图片内容解析成字节数组,将字节数组转换为ImageView可调用的Bitmap对象,图片缩放,把字节数组保存为一个文件,把Bitmap转Byte
- 把一个DataTable对象转换成一个数组对象
- Cracking coding interview(4.3)给定一个排好序的数组创建最小高度的二叉树
- 将2乘3的二维数组a的行和列的元素转换,存到一个3乘2的数组里。
- 输入一个数组,判断该数组是否是某二叉树的前序遍历结果
- PHP递归方式把一个数组里面的null转换为空字符串”的方法
- BUAA 2014级数据结构第五次上机 二叉树之数组转换广义表
- 用javascript对一个json数组深度赋值示例