Original title:

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:Given the sorted array: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 0 / \ -3 9 / / -10 5

The biggest lesson I learned from this problem is that memory application still needs to use new. malloc support is not very good. There is also a problem in this problem itself, that is, it can only be solved in the form of its search tree. Other solutions that are also balanced binary search trees cannot be solved. For example, if the result in the example is replaced by:

0 / \ -10 5 \ \ -3 9

I can't. I use a similar binary search method here. The result is:

Success

Runtime: 8 ms, faster than 100.00% of C++ online submissions for Convert Sorted Array to Binary Search Tree.

Memory Usage: 21.2 MB, less than 42.89% of C++ online submissions for Convert Sorted Array to Binary Search Tree.

Code:

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* sortedArrayToBST(vector<int>& nums) { int l=0; int r=nums.size()-1; if(r==-1){return NULL;} int m=(l+r+1)/2; TreeNode *t=new TreeNode(nums[m]); t->val=nums[m]; t->left=NULL; t->right=NULL; BST(t,nums,l,m-1,true); BST(t,nums,m+1,r,false); return t; } void BST(TreeNode* tn,vector<int>& nums,int l,int r,bool left){ if(l>r){return;} int m=(l+r+1)/2; TreeNode* neo=new TreeNode(nums[m]); neo->val=0; neo->left=NULL; neo->right=NULL; if(left){tn->left=neo;} else tn->right=neo; neo->val=nums[m]; BST(neo,nums,l,m-1,true); BST(neo,nums,m+1,r,false); } };

The memory occupation is a little high. In fact, circular call can reduce the occupation, but it is not written due to time. For reference, you can go to the discussion area to see a lot of simple writing algorithms.