首页 > 代码库 > leetcode--Convert Sorted List to Binary Search Tree
leetcode--Convert Sorted List to Binary Search Tree
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | public class Solution { /** Convert the linked list to arrayList first, and then convert the ArrayList to a BST * @param head --head node of the linked list * @return TreeNode --the root node of a height balanced BST tree * @author Averill Zheng * @version 2014-06-05 * @since JDK 1.7 */ public TreeNode sortedListToBST(ListNode head) { TreeNode root = null ; ArrayList<Integer> number = new ArrayList<Integer>(); int length = 0 ; while (head != null ){ number.add(head.val); head = head.next; ++length; } root = convertHelper(number, 0 , length); return root; } private TreeNode convertHelper(ArrayList<Integer> number, int i, int j){ TreeNode root = null ; if (j > i){ if (j == i + 1 ) root = new TreeNode(number.get(i)); else { int mid = i + (j - i) / 2 ; root = new TreeNode(number.get(mid)); root.left = convertHelper(number,i, mid); root.right = convertHelper(number, mid + 1 , j); } } return root; } } |
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。