1. 程式人生 > >Crack LeetCode 之 108. Convert Sorted Array to Binary Search Tree

Crack LeetCode 之 108. Convert Sorted Array to Binary Search Tree

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

把有序陣列轉為二叉查詢樹,本質上就是對陣列做二分查詢,中間元素就是根;然後在對左右兩個分割槽迭代二分查詢。本題可以用遞迴函式來解。c++程式碼如下,空間複雜度是O(logn),時間複雜度是O(n)。

class Solution {
public:
    TreeNode * sortedArrayToBST(vector<int>& nums) {
        if (nums.empty())
            return NULL;

        return helper(nums, 0, nums.size());
    }

    TreeNode * helper(vector<int>& nums, int start, int end)
    {
        if (nums.empty() || start >= end)
            return NULL;

        TreeNode * res = new TreeNode(nums[(start+end)/2]);
        res->left = helper(nums, start, (start + end) / 2);
        res->right = helper(nums, (start + end) / 2 + 1, end);
        return res;
    }
};