Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
==============
升序数组a[],构造平衡二叉树,左右子树高度差不超过1.
思路:
利用先序构建二叉树的方法,将数组的中间节点a[mid]作为根节点root的值,
root的左子树由a[0,...mid-1]构造
root的右子树由a[mid+1,...a.size-1]构造
最后返回root
===========
/** * 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){ if(nums.empty()) return nullptr; TreeNode *root = help_saTobst(nums,0,nums.size()-1); return root; } TreeNode* help_saTobst(vector<int> &nums,int s,int end){ if(s>end) return nullptr; int mid = (s+end)/2; TreeNode *root = new TreeNode(nums[mid]); root->left = help_saTobst(nums,s,mid-1); root->right = help_saTobst(nums,mid+1,end); return root; } };