這題要把陣列轉成一個二元樹。
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 練習外,我也入手了這本,題庫來自真正的面試,並非摘自教科書。它們反映出頂尖公司真正會出的題目,你可以藉此做好充分準備。
需要的話可以看看,寫得很仔細。
需要的話可以看看,寫得很仔細。
沒有留言:
張貼留言