Convert Sorted Array to Binary Search Tree
2014.1.8 02:11
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Solution:
A height balanced binary tree is a binary tree, whose heights of left and right subtrees varie by at most 1. Thus constructing such a tree from a sorted array can be done by cutting the array by half and picking the middle element as the root.
Note that the inorder traversal of a BST is a sorted array, that should help you figure out how the method works.
Do this procedure recursively and the job is done.
Time and space complexities are both O(n), where n is the number of elements in the array. Space complexity comes from local parameters in function calls.
Accepted code:
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode *sortedArrayToBST(vector<int> &num) { 13 // Note: The Solution object is instantiated only once and is reused by each test case. 14 if(num.size() <= 0){ 15 return nullptr; 16 }else{ 17 return constructBSTFromArray(num, 0, (int)(num.size() - 1)); 18 } 19 } 20 private: 21 TreeNode *constructBSTFromArray(vector<int> &num, int left, int right) { 22 int mid; 23 TreeNode* root; 24 25 if(left > right){ 26 return nullptr; 27 } 28 29 mid = (right - left) / 2 + left; 30 root = new TreeNode(num[mid]); 31 root->left = constructBSTFromArray(num, left, mid - 1); 32 root->right = constructBSTFromArray(num, mid + 1, right); 33 34 return root; 35 } 36 };