C++實(shí)現(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)為二叉搜索樹,所謂二叉搜索樹,是一種始終滿足左<根<右的特性,如果將二叉搜索樹按中序遍歷的話,得到的就是一個(gè)有序數(shù)組了。那么反過來,我們可以得知,根節(jié)點(diǎn)應(yīng)該是有序數(shù)組的中間點(diǎn),從中間點(diǎn)分開為左右兩個(gè)有序數(shù)組,在分別找出其中間點(diǎn)作為原中間點(diǎn)的左右兩個(gè)子節(jié)點(diǎn),這不就是是二分查找法的核心思想么。所以這道題考的就是二分查找法,代碼如下:
解法一:
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ù)是一個(gè)數(shù)組,所以當(dāng)把輸入數(shù)組的中間數(shù)字取出來后,需要把所有兩端的數(shù)組組成一個(gè)新的數(shù)組,并且分別調(diào)用遞歸函數(shù),并且連到新創(chuàng)建的cur結(jié)點(diǎn)的左右子結(jié)點(diǎn)上面,參見代碼如下:
解法二:
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++實(shí)現(xiàn)LeetCode(108.將有序數(shù)組轉(zhuǎn)為二叉搜索樹)的文章就介紹到這了,更多相關(guān)C++實(shí)現(xiàn)將有序數(shù)組轉(zhuǎn)為二叉搜索樹內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用C語言實(shí)現(xiàn)CRC校驗(yàn)的方法
本篇文章是對使用C語言實(shí)現(xiàn)CRC校驗(yàn)的方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05C++ txt 文件讀取,并寫入結(jié)構(gòu)體中的操作
這篇文章主要介紹了C++ txt 文件讀取,并寫入結(jié)構(gòu)體中的操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12C語言超詳細(xì)講解字符串函數(shù)和內(nèi)存函數(shù)
這篇文章主要介紹一些c語言中常用字符串函數(shù)和內(nèi)存函數(shù)的使用,字符串函數(shù)(String?processing?function)也叫字符串處理函數(shù),指的是編程語言中用來進(jìn)行字符串處理的函數(shù)2022-05-05C++的template模板中class與typename關(guān)鍵字的區(qū)別分析
這篇文章中我們來談一談C++的template模板中class與typename關(guān)鍵字的區(qū)別分析,同時(shí)會(huì)講到嵌套從屬名稱時(shí)的一些注意點(diǎn),需要的朋友可以參考下2016-06-06C語言從基礎(chǔ)到進(jìn)階全面講解數(shù)組
數(shù)組是一組有序的數(shù)據(jù)的集合,數(shù)組中元素類型相同,由數(shù)組名和下標(biāo)唯一地確定,數(shù)組中數(shù)據(jù)不僅數(shù)據(jù)類型相同,而且在計(jì)算機(jī)內(nèi)存里連續(xù)存放,地址編號(hào)最低的存儲(chǔ)單元存放數(shù)組的起始元素,地址編號(hào)最高的存儲(chǔ)單元存放數(shù)組的最后一個(gè)元素2022-05-05