Convert Sorted Array to Binary Search Tree

描述

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

分析

二分法。

代码

// Convert Sorted Array to Binary Search Tree
// 二分法,时间复杂度O(n),空间复杂度O(logn)
class Solution {
public:
    TreeNode* sortedArrayToBST (vector& num) {
        return sortedArrayToBST(num.begin(), num.end());
    }

    template
    TreeNode* sortedArrayToBST (RandomAccessIterator first,
            RandomAccessIterator last) {
        const auto length = distance(first, last);

        if (length left = sortedArrayToBST(first, mid);
        root->right = sortedArrayToBST(mid + 1, last);

        return root;
    }
};

相关题目

results matching ""

    No results matching ""