Convert Sorted Array to Binary Search Tree

1.题目描述

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

 

2.解法分析

如果是数组,这个题目就是个二分查找的过程,不断寻找当前的树根。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode *sortedArrayToBST(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int len = num.size();
        if(!len)return NULL;
        return mySortedArrayToBST(num,0,len-1);
    }
    
    TreeNode *mySortedArrayToBST(vector<int> &num,int start,int end)
    {
        if(start>end)return NULL;
        int mid = (start+end)/2;
        TreeNode * parent = new TreeNode(num[mid]);
        parent->left = mySortedArrayToBST(num,start,mid-1);
        parent->right = mySortedArrayToBST(num,mid+1,end);
    }
};
posted @ 2013-08-15 00:02  曾见绝美的阳光  阅读(211)  评论(0编辑  收藏  举报