Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
这个问题比较简单,用递归是个不错的选择,我的C++代码实现如下:
class Solution { public: TreeNode *sortedArrayToBST(vector<int> &num) { return num.empty() ? nullptr : sortedArrayToBST(num, 0, num.size() - 1); } private: TreeNode *sortedArrayToBST(vector<int> &num, int start, int end) { int mid = (start + end) >> 1; TreeNode *root = new TreeNode(num[mid]); if (start < mid) root->left = sortedArrayToBST(num, start, mid - 1); if (mid < end) root->right = sortedArrayToBST(num, mid + 1, end); return root; } };
时间性能如下图所示:
LeetCode[Tree]: Convert Sorted Array to Binary Search Tree
原文地址:http://blog.csdn.net/chfe007/article/details/42153475