https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/7/trees/51/
将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
转化成平衡二叉搜索树,也就是说树的每个节点 的左右两个子树的高度差的绝对值不超过 1。
因为数组是有序的,而BST的性质是左子树所有节点小于根,右子树所有节点大于根,所以很容易想到从有序数组的一半处选取根节点,然后所有左侧元素就是左子树,右侧元素就是右子树,然后分别从左侧和右侧选取中间元素。。。
这是一个递归的思路,实现上也不复杂。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* construct_node( int * nums, int l, int r);
struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
struct TreeNode* root;
root = construct_node( nums, 0, numsSize-1);
return root;
}
struct TreeNode* construct_node( int * nums, int l, int r){
if (l<=r){
int p=(l+r)/2;
struct TreeNode* n = malloc(sizeof(struct TreeNode));
n->val = nums[p];
n->left = construct_node( nums, l,p-1);
n->right = construct_node(nums, p+1, r);
return n;
}
return NULL;
}