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; }