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.
public TreeNode sortedListToBST(ListNode head) { if(head == null) return null; ListNode safehead = new ListNode(0); safehead.next = head; ListNode prev = safehead; ListNode p = head; while( p != null && p.next != null){ p = p.next.next; prev = prev.next; } TreeNode root = new TreeNode(prev.next.val); p = prev.next.next; prev.next = null; root.left = sortedListToBST(safehead.next); root.right = sortedListToBST(p); return root; }
No comments:
Post a Comment