溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C++怎么將有序數(shù)組轉為二叉搜索樹

發(fā)布時間:2022-03-28 15:34:02 來源:億速云 閱讀:175 作者:iii 欄目:大數(shù)據(jù)

本篇內(nèi)容介紹了“C++怎么將有序數(shù)組轉為二叉搜索樹”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!

將有序數(shù)組轉為二叉搜索樹

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 

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

解法一:

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;
    }
};

我們也可以不使用額外的遞歸函數(shù),而是在原函數(shù)中完成遞歸,由于原函數(shù)的參數(shù)是一個數(shù)組,所以當把輸入數(shù)組的中間數(shù)字取出來后,需要把所有兩端的數(shù)組組成一個新的數(shù)組,并且分別調(diào)用遞歸函數(shù),并且連到新創(chuàng)建的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;
    }
};

“C++怎么將有序數(shù)組轉為二叉搜索樹”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關的知識可以關注億速云網(wǎng)站,小編將為大家輸出更多高質量的實用文章!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

c++
AI