Convert Sorted Array to Binary Search Tree [LEETCODE]
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
============================================================================================
If you would have to choose an array element to be the root of a balanced BST, which element would you pick? The root of a balanced BST should be the middle element from the sorted array.
You would pick the middle element from the sorted array in each iteration. You then create a node in the tree initialized with this element. After the element is chosen, what is left? Could you identify the sub-problems within the problem?
There are two arrays left — The one on its left and the one on its right. These two arrays are the sub-problems of the original problem, since both of them are sorted. Furthermore, they are subtrees of the current node’s left and right child.
The code below creates a balanced BST from the sorted array in O(N) time (N is the number of elements in the array). Compare how similar the code is to a binary search algorithm. Both are using the divide and conquer methodology.
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 return arrayToBST(num, 0, num.size()); 15 } 16 TreeNode *arrayToBST(vector<int> &num, int start, int end) { 17 if(end - start <= 0) { 18 return NULL; 19 } 20 int mid = start + (end - start) / 2; 21 TreeNode *root = new TreeNode(num[mid]); 22 root->left = arrayToBST(num, start, mid); 23 root->right = arrayToBST(num, mid + 1, end); 24 return root; 25 26 } 27 };

浙公网安备 33010602011771号