标签:
思路很简单,用二分法,每次选中间的点作为根结点,用左、右结点递归。
TreeNode* sortedArrayToBST(vector<int> &num) { return sortedArrayToBST(num.begin(), num.end()); } template<typename RandomAccessIterator> TreeNode* sortedArrayToBST(RandomAccessIterator first, RandomAccessIterator last) { const auto length = distance(first, last); if (length <= 0)return nullptr; auto mid = first + length / 2; TreeNode *root = new TreeNode(*mid); root->left = sortedArrayToBST(first, mid); root->right = sortedArrayToBST(mid, last); return root; }
Leetcode 之Convert Sorted Array to Binary Search Tree(54)
标签:
原文地址:http://www.cnblogs.com/573177885qq/p/5594322.html