Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
// Node 생성
struct TreeNode* newNode(int val){
struct TreeNode* new = malloc(sizeof(struct TreeNode));
new->val = val;
new->left = NULL;
new->right = NULL;
return new;
}
// BST 만들기
struct TreeNode* ArrayToBST(int* nums, int start, int end){
if(start>end)
return NULL;
// sorted array가 주어지므로
int mid = (start+end)/2;
struct TreeNode* root = newNode(nums[mid]);
root->left = ArrayToBST(nums,start,mid-1);
root->right = ArrayToBST(nums,mid+1,end);
return root;
}
struct TreeNode* sortedArrayToBST(int* nums, int numsSize){
// 배열 크기 생각 (0 ~ numsSize-1)
return ArrayToBST(nums, 0, numsSize-1);
}
// !!!!! sorted array가 주어지므로 !!!!!
int mid = (start+end)/2;
struct TreeNode* root = newNode(nums[mid]);
root->left = ArrayToBST(nums,start,mid-1);
root->right = ArrayToBST(nums,mid+1,end);
이진트리.. 다 까먹었다..