Given an array where elements is sorted in ascending order, convert it to a height balanced BST.
To tell a sorted array into a binary search tree, this question did not come out, basically refer to others, boundary conditions should pay attention to:
1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: Atreenode* Sortedarraytobst (vector<int>&nums) { - returnCreatetree (Nums,0, Nums.size ()-1); - } the -TreeNode * Createtree (vector<int> & Nums,intLeftintRight ) - { - if(Left >Right ) + returnNULL; - intMid = left + (right-left)/2; +TreeNode * Leftnode = Createtree (Nums, left, mid-1); ATreeNode * Rightnode = Createtree (nums, Mid +1, right); atTreeNode * tmproot=NewTreeNode (Nums[mid]); -Tmproot->left =Leftnode; -Tmproot->right =Rightnode; - returnTmproot; - } -};
Leetcode oj:convert Sorted array to binary search tree (converts sorted arrays to binary searching trees)