leetcode地址:node
https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description/數組
難度:中等this
描述:code
Given a singly linked list 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.ip
Example:element
Given the sorted linked list: [-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
解題思路:
分爲兩步:leetcode
1. 把鏈表轉存到一個數組中,問題轉化爲:將一個有序數組轉化爲一個平衡二叉查找樹。it
2. 取數組的中點爲根節點,那麼根節點的左子樹是由左半邊的數組生成的,右子樹是由數組右半邊生成的,分別對數組左半邊和右半邊進行遞歸調用io
代碼:
public class SortedListToBST { public TreeNode sortedListToBST(ListNode head) { int size = 0; ListNode p = head; while (p != null) { size++; p = p.next; } ListNode[] listNodes = new ListNode[size]; p = head; int index = 0; while (p != null) { listNodes[index++] = p; p = p.next; } return sortedListToBST(listNodes, 0, listNodes.length); } public TreeNode sortedListToBST(ListNode[] listNodes, int start, int end) { if (start >= end) { return null; } int mid = (end + start) / 2; TreeNode root = new TreeNode(listNodes[mid].val); root.left = sortedListToBST(listNodes, start, mid); root.right = sortedListToBST(listNodes, mid + 1, end); return root; }}