convert-sorted-array-to-binary-search-tree

时间:2021-10-27 20:04:51

题目描述

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

 

/**
 * 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 *build(vector<int>&num,int start,int end) {
        if(start>=end) {
            return NULL;
        }
        int mid=start+(end-start)/2;
        TreeNode *node=new TreeNode(num[mid]);
        node->left=build(num,start,mid);
        node->right=build(num,mid+1,end);
    	return node;
    }
    
    TreeNode *sortedArrayToBST(vector<int> &num) {
        if(num.size()==0)	return NULL;
        return build(num,0,num.size());
    }
    
};

  

 

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