LeetCode题目:Convert Sorted Array to Binary Search Tree

By | 2012 年 12 月 13 日

对排序的数组进行二分查找样式的遍历就行了。



Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.



代码:84ms过大集合

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    TreeNode *sortedArrayToBST(vector &num,int si, int ei) {
        if(si > ei) return NULL;
        int mid = (ei + si) / 2;
        TreeNode *root = new TreeNode(num[mid]);
        root->left = sortedArrayToBST(num,si,mid - 1);
        root->right = sortedArrayToBST(num,mid + 1,ei);
        return root;
    }
    
public:
    TreeNode *sortedArrayToBST(vector &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        return sortedArrayToBST(num,0,num.size() - 1);
    }
};

发表评论

电子邮件地址不会被公开。 必填项已用*标注