Given a singly linked list where elements is sorted in ascending order, convert it to a height balanced BST.
Since it is already ordered, the binary method is used to create this balanced binary tree, with the Sort List similar
Note that the second half of a chain of the index range is [0,high-mid-1], the original has been tangled in the high-mid;
The second is to note the chain head of the latter half chain.
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int x) {val = x; next = null;} *} *//** * Definition for Binary tree * public class TreeNode {* Int. val; * TreeNode left, * TreeNode right; * TreeN Ode (int x) {val = x;} *} */public class Solution {public TreeNode Sortedlisttobst (ListNode head) {int len = 0; ListNode p = head; while (P! = null) {len++; p = p.next; } return Create (head,0,len-1); Public TreeNode Create (ListNode head, Int. Low, int.) {if (Low > high) {return null; } int mid = (low + high) >> 1; int count = 0; ListNode p = head; while (Count < mid) {p = p.next; count++; } TreeNode t = new TreeNode (p.val); T.left = Create (head,0,mid-1); T.right = Create (p.next,0,high-mid-1); return t; }}
Runtime: 281 Ms
Convert Sorted List to Binary Search Tree