Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
思路比较简单,就是每次以中位数为根节点,然后左边即左子树,右边是右子树,递归下去即可
超时代码(不知道为啥):
class Solution{ public: void dfs(TreeNode* &root,vector<int> num,int start,int end){ int mid=(start+end)/2; root=new TreeNode(num[mid]); if(start<=mid-1) dfs(root->left,num,start,mid-1); if(mid+1<=end) dfs(root->right,num,mid+1,end); return; } TreeNode *sortedArrayToBST(vector<int> &num) { if(num.empty()) return NULL; TreeNode* root=NULL; dfs(root,num,0,num.size()-1); return root; } };
AC代码:
class Solution{ public: TreeNode *createTree(vector<int> &num, int start, int end) { // if (start > end) return NULL; int mid = (start+end)/2; TreeNode *node = new TreeNode(num[mid]); if(start<=mid-1) node->left = createTree(num, start, mid-1); if(mid+1<=end) node->right = createTree(num, mid+1, end); return node; } TreeNode *sortedArrayToBST(vector<int> &num) { if(num.empty()) return NULL; return createTree(num,0,num.size()-1); } };