美文网首页
108. Convert Sorted Array to Bin

108. Convert Sorted Array to Bin

作者: juexin | 来源:发表于2017-01-07 14:10 被阅读0次

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

class Solution {
public:
    TreeNode* createTree(vector<int>& nums,int left,int right)
    {
        if(left>right)
          return NULL;
          
        int mid = (left+right)>>1;
        TreeNode* leftNode = createTree(nums,left,mid-1);
        TreeNode* rightNode = createTree(nums,mid+1,right);
        
        TreeNode* node = new TreeNode(nums[mid]);
        node->left = leftNode;
        node->right = rightNode;
        
        return node;
    }
    
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return createTree(nums,0,nums.size()-1);
    }
};

相关文章

网友评论

      本文标题:108. Convert Sorted Array to Bin

      本文链接:https://www.haomeiwen.com/subject/xwdfbttx.html