[LeetCode] 109. 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.
Thought process:
Divide and conquer. Recursively find the middle of the list and attach left and right sub-tree. Use an instance variable as current pointer to avoid looking for middle point in every recurrence.
Solution:
Time complexity:
Current moves from the start to the end only once. The time complexity is O(n).
Thought process:
Divide and conquer. Recursively find the middle of the list and attach left and right sub-tree. Use an instance variable as current pointer to avoid looking for middle point in every recurrence.
Solution:
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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { private ListNode current; public TreeNode sortedListToBST(ListNode head) { current = head; int length = 0; while (current != null) { length++; current = current.next; } current = head; return sortedListToBST(length); } private TreeNode sortedListToBST(int length) { if (length == 0) { return null; } TreeNode left = sortedListToBST(length / 2); TreeNode root = new TreeNode(current.val); current = current.next; TreeNode right = sortedListToBST(length - length / 2 - 1); root.left = left; root.right = right; return root; } } |
Time complexity:
Current moves from the start to the end only once. The time complexity is O(n).
Comments
Post a Comment