4.3 Given a sorted (increasing order) array, write an algorithm to createa binary tree with minimal height.
译文:给定一个有序数组(递增),写出一个算法来构建一棵具有最小高度的二叉树
有限个节点来构建一棵具最小高度的二叉树,需要把这些结点均匀分布在“根”(父)点的左右。即对于任意结点,它的左子树和右子树的结点的数量应该相当。对于本题来说,理想的情况就是,将有序数组对半分,以中间值作为根节点,左边的数值作为左子树,右边的数值作为右子树,将数组左边的数值和右边的树再分别进行对半分,不断递归,直到不可再分。那么,最后得到的这颗二叉树也将是一棵平衡二叉树。
题目比较简单,直接贴出代码:
#include <iostream>
using namespace std;
typedef struct _BinaryTree
{
int value;
struct _BinaryTree *left_child; //左儿子
struct _BinaryTree *right_child;
}BinaryTree;
BinaryTree* addToTree(int arr[], int start, int end)
{
if (start > end)
return NULL;
int mid = start + ((end - start) >> 1);//避免溢出
BinaryTree *Node = new BinaryTree;
Node->value = arr[mid];//数组中值
Node->left_child = addToTree(arr, start, mid - 1);//左子树
Node->right_child = addToTree(arr, mid + 1, end);//右子树
return Node;
}
BinaryTree* createMinimalBST(int arr[], int length)
{
return addToTree(arr, 0, length - 1);
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int length = sizeof(arr) / sizeof(arr[0]);
BinaryTree *Tree = createMinimalBST(arr, length);
return 0;
}
仔细一看,上面的实现方法实际上也是我们之前讨论过的深度优先搜索
DFS:先把所有左子树走到底,然后回来一层再走,直到所有左子树走完,再去右子树进行同样的走法。