解题思路:
1. 取有序数组的中间节点,作为二叉树的根节点。
2. 将数组的前半部分作为左子树,后半部分作为右子树,递归调用。
#include <stdio.h>
#include <stdlib.h>
typedef struct _BinaryTree {
int value;
struct _BinaryTree *left;
struct _BinaryTree *right;
}BinaryTree;
static void SortedArrayToBinaryTree(BinaryTree **root, int *arr, int begin, int end)
{
if(begin <= end)
{
int mid = (begin + end)>>1;
BinaryTree *node;
node = malloc(sizeof(BinaryTree));
node->value = arr[mid];
SortedArrayToBinaryTree(&node->left, arr, begin, mid-1);
SortedArrayToBinaryTree(&node->right, arr, mid+1, end);
*root = node;
}
else
{
*root = NULL;
}
}
static void PrintTreeWithLeftFirst(BinaryTree *root)
{
if(root != NULL)
{
PrintTreeWithLeftFirst(root->left);
printf("%d, ", root->value);
PrintTreeWithLeftFirst(root->right);
}
}
int main()
{
int a[] = {1,2,3,4,5,6,7,8,9};
BinaryTree *root;
SortedArrayToBinaryTree(&root, a, 0, 8);
PrintTreeWithLeftFirst(root);
return 0;
}