首页 > 代码库 > LeetCode[Tree]: Convert Sorted Array to Binary Search Tree

LeetCode[Tree]: Convert Sorted Array to Binary Search Tree

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