void toBST(TreeNode*& root, vector<int>& nums, int start, int end){ if(start <= end){ int mid = start + (end - start)/2; root = new TreeNode(nums[mid]); toBST(root -> left, nums, start, mid - 1); toBST(root -> right, nums, mid + 1, end); } }
// O(n) TreeNode* Solution::toBST(ListNode* &head, int start, int end) { if (start>end) return NULL; int mid = (start + end)/2; TreeNode* left = toBST(head, start, mid-1); TreeNode* root = new TreeNode(head->val); root->left = left; head = head->next; TreeNode* right = toBST(head, mid+1, end); root->right = right; return root; }
struct node* toBST(int *arr, int start, int end) { int mid, value; if (start > end) return NULL; mid = (start + end) / 2; struct node *root = createNode(arr[mid]); root->left = toBST(arr, start, mid - 1); root->right = toBST(arr, mid + 1, end); return root; }
TreeNode* Solution::sortedListToBST2(ListNode *head) { int n = 0; ListNode* node = head; while (node) { node = node->next; n++; } return toBST(head, 0, n-1); }
/** * @param A: A sorted (increasing order) array * @return: A tree node */ TreeNode *sortedArrayToBST(vector<int> &A) { int n = static_cast<int>(A.size()); if (n == 0) return NULL; return toBST(A, 0, n - 1); }
TreeNode* sortedArrayToBST(vector<int>& nums) { int n = nums.size(); TreeNode* root = NULL; toBST(root, nums, 0, n-1); return root; }
struct node * convert_array_to_bst(int *arr, int len){ if (arr == NULL) return NULL; return toBST(arr, 0, len - 1); }