首页 > 代码库 > Convert Sorted Array to Binary Search Tree

Convert Sorted Array to Binary Search Tree

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

思路:取数组的中点为树的根,前半部分为左子树,后半部分为右子树。

 1 class Solution { 2 public: 3     TreeNode *sortedArrayToBST( vector<int> &num ) { 4         return ConvertSubArray( num, 0, (int)num.size()-1 ); 5     } 6 private: 7     TreeNode *ConvertSubArray( vector<int> &num, int start, int end ) { 8         if( start > end ) { return 0; } 9         int middle = ( start + end ) / 2;10         TreeNode *treeNode = new TreeNode( num[middle] );11         treeNode->left = ConvertSubArray( num, start, middle-1 );12         treeNode->right = ConvertSubArray( num, middle+1, end );13         return treeNode;14     }15 };