問題定義:
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;
- }