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ù)組,所以當把輸入數(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)文章
C++ txt 文件讀取,并寫入結(jié)構(gòu)體中的操作
這篇文章主要介紹了C++ txt 文件讀取,并寫入結(jié)構(gòu)體中的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12C語言超詳細講解字符串函數(shù)和內(nèi)存函數(shù)
這篇文章主要介紹一些c語言中常用字符串函數(shù)和內(nèi)存函數(shù)的使用,字符串函數(shù)(String?processing?function)也叫字符串處理函數(shù),指的是編程語言中用來進行字符串處理的函數(shù)2022-05-05C++的template模板中class與typename關(guān)鍵字的區(qū)別分析
這篇文章中我們來談一談C++的template模板中class與typename關(guān)鍵字的區(qū)別分析,同時會講到嵌套從屬名稱時的一些注意點,需要的朋友可以參考下2016-06-06