Given an array where elements is sorted in ascending order, convert it to a height balanced BST.
Idea: Using the dichotomy method, the middle node of the list is used as the root node, then the left half of the list and the right half are processed separately, recursively.
structTreeNode {intVal; TreeNode*Left ; TreeNode*Right ; TreeNode (intx): Val (x), left (null), right (null) {}};classSolution { Public: TreeNode*sortedarraytobst (vector<int> &num) { if(Num.empty ())returnNULL; TreeNode* Root =NewTreeNode (0); DFS (NUM,0, Num.size ()-1, Root); returnRoot; } voidDFS (vector<int> &num,intStartintend,treenode*TreeNode) { intSize = end-start+1; if(Size = =1) {TreeNode->val =Num[start]; return; } intMID = size/2+start; TreeNode->val =Num[mid]; TreeNode->left =NewTreeNode (0); DFS (Num,start,mid-1,treenode->Left ); if(mid+1<=end) {TreeNode->right =NewTreeNode (0); DFS (Num,mid+1,end,treenode->Right ); } }};
108.Convert Sorted Array to Binary Search Tree (array; Divide-and-conquer, DFS)