76:Convert Sorted Array to Binary Search Tree

来源:互联网 发布:yum error14 curl 37 编辑:程序博客网 时间:2024/05/17 18:46

题目:Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

该题目可以使用二分法,代码如下:

// 递归法,时间复杂度 O(log n)class Solution {public:        TreeNode* sortedArrayToBST(vector<int>& nums) {                return sortedArrayToBST(nums.begin(), nums.end());        }private:        template <class InputIterator>        TreeNode* sortedArrayToBST(InputIterator first, InputIterator last) {                if (first == last) return nullptr;                auto size = distance(first, last);                auto mid = next(first, size / 2);                auto left_tree = sortedArrayToBST(first, mid);                auto right_tree = sortedArrayToBST(next(mid), last);                TreeNode* root = new TreeNode{*mid};                root -> left = left_tree;                root -> right = right_tree;                return root;        }};
0 0
原创粉丝点击