C++實現(xiàn)LeetCode(108.將有序數(shù)組轉(zhuǎn)為二叉搜索樹)
[LeetCode] 108.Convert Sorted Array to Binary Search Tree 將有序數(shù)組轉(zhuǎn)為二叉搜索樹
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ù)組轉(zhuǎn)為二叉搜索樹,所謂二叉搜索樹,是一種始終滿足左<根<右的特性,如果將二叉搜索樹按中序遍歷的話,得到的就是一個有序數(shù)組了。那么反過來,我們可以得知,根節(jié)點應(yīng)該是有序數(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ù)組,所以當(dāng)把輸入數(shù)組的中間數(shù)字取出來后,需要把所有兩端的數(shù)組組成一個新的數(shù)組,并且分別調(diào)用遞歸函數(shù),并且連到新創(chuàng)建的cur結(jié)點的左右子結(jié)點上面,參見代碼如下:
解法二:
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/
到此這篇關(guān)于C++實現(xiàn)LeetCode(108.將有序數(shù)組轉(zhuǎn)為二叉搜索樹)的文章就介紹到這了,更多相關(guān)C++實現(xiàn)將有序數(shù)組轉(zhuǎn)為二叉搜索樹內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
淺談十進制小數(shù)和二進制小數(shù)之間的轉(zhuǎn)換
下面小編就為大家?guī)硪黄獪\談十進制小數(shù)和二進制小數(shù)之間的轉(zhuǎn)換。小編覺得挺不錯的現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01

