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);
    }
};

你可能感兴趣的:(Binary search)