Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Solution:
public class Solution { public TreeNode sortedListToBST(ListNode head) { if (head == null) return null; if (head.next == null) return new TreeNode(head.val);
ListNode headcopy = head; ListNode next = head; ListNode leftend = head; while (next.next.next != null){ next = next.next.next; leftend = headcopy; headcopy = headcopy.next; if (next.next == null) break; } ListNode right = headcopy.next; leftend.next = null;
LeetCode Convert Sorted List to Binary Search Tree
Convert Sorted List to Binary Search TreeGiven a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.Solution: