Convert Sorted Array to Binary Search Tree

来源:互联网 发布:玻璃优化软件破解版 编辑:程序博客网 时间:2024/06/05 09:44

Convert Sorted Array to Binary Search Tree

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

遇到排序数组,要想到二分查找:

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+1,last);        return root;    }


0 0