[LeetCode] Convert Sorted Array to Binary Search Tree 將有序數組轉為二叉搜索樹


 

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

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of everynode never differ by more than 1.

Example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

 

這道題是要將有序數組轉為二叉搜索樹,所謂二叉搜索樹,是一種始終滿足左<根<右的特性,如果將二叉搜索樹按中序遍歷的話,得到的就是一個有序數組了。那么反過來,我們可以得知,根節點應該是有序數組的中間點,從中間點分開為左右兩個有序數組,在分別找出其中間點作為原中間點的左右兩個子節點,這不就是是二分查找法的核心思想么。所以這道題考的就是二分查找法,代碼如下:

 

解法一:

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

 

我們也可以不使用額外的遞歸函數,而是在原函數中完成遞歸,由於原函數的參數是一個數組,所以當把輸入數組的中間數字取出來后,需要把所有兩端的數組組成一個新的數組,並且分別調用遞歸函數,並且連到新創建的cur結點的左右子結點上面,參見代碼如下:

 

解法二:

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

 

類似題目:

Convert Sorted List to Binary Search Tree

 

參考資料:

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/discuss/35220/My-Accepted-Java-Solution

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/discuss/35394/6-lines-Java-Accepted-Solution

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM