iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 21
0
自我挑戰組

刷題記錄與人生分享系列 第 21

DAY21 Convert Sorted Array to Binary Search Tree

  • 分享至 

  • xImage
  •  

題目:

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
將一個排序好的陣列轉成二元樹。

解題思路:

利用二分法找尋每個的根節點,並搭配遞迴將其左右依序找出,直到二分法條件不符合就回傳。

C版本:

struct TreeNode* convert(int* nums,int start,int end)
{
     if(start > end)
          return NULL;
     else{
         int mid = (start+end)/2;
         struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
         node->val = nums[mid];
         node->left = convert(nums,start,mid-1);
         node->right = convert(nums,mid+1,end);
         return node;
     }
}

struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
    return convert(nums,0,numsSize-1);
}

Javascript版本:

var sortedArrayToBST = function(nums) {
    return traveler(nums, 0, nums.length)
};

var traveler = function(temp, start, end)
{
    if(start >= end)
        return null
    else
    {
        var mid = Math.floor((start+end) / 2);
        var result = new TreeNode(temp[mid]);
        result.left = traveler(temp, start, mid)
        result.right = traveler(temp, mid+1, end)
        return result;
    }    
};

程式Github分享:

https://github.com/SIAOYUCHEN/leetcode

相似主題分享:

https://ithelp.ithome.com.tw/users/20100009/ironman/2500
https://ithelp.ithome.com.tw/users/20113393/ironman/2169
https://ithelp.ithome.com.tw/users/20107480/ironman/2435
https://ithelp.ithome.com.tw/users/20107195/ironman/2382
https://ithelp.ithome.com.tw/users/20119871/ironman/2210
https://ithelp.ithome.com.tw/users/20106426/ironman/2136

本日分享:

Giving up is also a choice. Giving up is not incompetent because you have a better choice. Sometimes, giving up is more courage than persistence.
放棄同樣是一種選擇,放棄並不是自己無能,而是因為自己有了更好的選擇。有時候,放棄比堅持還需要勇氣


上一篇
DAY20 Maximum Depth of Binary Tree
下一篇
DAY22 Sum Root to Leaf Numbers
系列文
刷題記錄與人生分享34
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言