您的位置:首页 > 其它

[Leetcode] Convert Sorted Array to Binary Search Tree

2014-10-22 10:20 411 查看
题目:

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

思路:类似二分法,中间向左右两边找child.

class Solution {
public:
    TreeNode* buildBST_helper(const vector<int>& num, int lower_bound, int upper_bound) {
        if (lower_bound > upper_bound) return nullptr;
        int mid = (lower_bound + upper_bound) / 2;
        TreeNode* new_root = new TreeNode(num[mid]);
        new_root->left = buildBST_helper(num, lower_bound, mid - 1);
        new_root->right = buildBST_helper(num, mid + 1, upper_bound);
        return new_root;
    }
    
    TreeNode *sortedArrayToBST(vector<int> &num) {
        return buildBST_helper(num, 0, num.size() - 1);
    }
};


总结:复杂度为O(n). 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: