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

108. Convert Sorted Array to Bin

作者: YellowLayne | 来源:发表于2017-06-19 16:36 被阅读0次

    1.描述

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

    2.分析

    3.代码

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
     * };
     */
     
    struct TreeNode* BST(int* nums, int from, int to) {
        if (from > to) return NULL;
        int mid = (from + to) / 2;
        struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
        node->val = nums[mid];
        node->left = BST(nums, from, mid - 1);
        node->right = BST(nums, mid + 1, to);
        return node;
    }
    
    struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
        if (NULL == nums || 0 >= numsSize) return NULL;
        return BST(nums, 0, numsSize - 1);
    }
    

    相关文章

      网友评论

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

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