![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEid6oa1UQTR-j4VEZi4noALDusPvioMi2lzotqHb81NjujwvSucorAmQeMufcn7Y6n8IvuUzyhK4ygpR6_WZ_RO3v8YXkeD7pQJZMFajsZyvw-jAuGn4Pueuig5zz91-vpBlJHWqOMPLygl/s280/photo-1485856407642-7f9ba0268b51.jpg)
這題要把陣列轉成一個二元樹。
LeetCode 題目連結
https://leetcode.com/problems/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 every node 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
Accept 作法
利用遞迴的方式不斷的把陣列分兩半,因為陣列已經排序好,再分配左子樹和右子樹。Runtime: 0 ms
Memory: 39.4 MB
Java 程式碼
class Solution { public TreeNode sortedArrayToBST(int[] nums) { return BST(nums,0,nums.length - 1); } TreeNode BST(int[] nums,int start,int end){ if(start > end){ return null; } int halfSize = (start+ end) /2; TreeNode node = new TreeNode(); node.val = nums[halfSize]; node.left = BST(nums,start,halfSize - 1); node.right = BST(nums,halfSize+1,end); return node; } }
更多 LeetCode 相關資源
複習程式面試書籍
除了 LeetCode 練習外,我也入手了這本,題庫來自真正的面試,並非摘自教科書。它們反映出頂尖公司真正會出的題目,你可以藉此做好充分準備。
需要的話可以看看,寫得很仔細。
需要的話可以看看,寫得很仔細。
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgoVeKbRaOIZW8Sl98-o0z-8qDJB24zstVfPK86W6ki_p2hFJfEZcTrx4ybrUg4gwrIAWyaJ1rw2ZkvUrda5b3OHsPt_nyzuxbgUk0VwoVdKpK7K3nN6HaW6lDb3mLlkLG1IahRsyzIODDf/s280/codinginterview.jpg)
沒有留言:
張貼留言