[leetcode]Convert Sorted Array to Binary Search Tree
直来直去的题目,注意用 l 和 r 两个下标来指示左右范围,并且用 if ( l > r ) 来作为递归出口,相比于用 start 和 len 来指示范围更优雅且不易出错。
class Solution { public: TreeNode *sortedArrayToBST(vector<int> &num, int l, int r){ if (num.size() < 1 || l < 0 || r > num.size()-1 || l > r) return NULL; int mid = (l+r)/2; TreeNode *root = new TreeNode(num[mid]); root->left = sortedArrayToBST(num, l, mid-1); root->right = sortedArrayToBST(num, mid+1, r); return root; } TreeNode *sortedArrayToBST(vector<int> &num) { // Start typing your C/C++ solution below // DO NOT write int main() function if (num.size() < 1) return NULL; return sortedArrayToBST(num, 0, num.size()-1); } };
EOF