Topic:
Given a singly linked list where elements is sorted in ascending order, convert it to a height balanced BST.
Puzzle: An ordered list into a binary sorting tree, if it is a relatively balanced sorting tree, it should be, the middle node of the list is the root node of the tree, the root node of the left subtree node should be the root node on the left side of the middle node, the right node of the root node should be the root node to the right of the part of the Followed by this rule and so on. Knowing the rules above, the key point of the problem is to find a linked list of the middle node, this should be very familiar with the speed of two pointers can be easily solved. Here is the implementation code for this idea:
Code:
Similar to merge sort O (NLOGN) public static TreeNode Sortedlisttobst (ListNode head) { ListNode fast=head; ListNode Slow=head; if (head==null)//recursive end condition return null; ListNode leftofmid=null;//is used to record the previous node of the middle node, where the slow point node is considered as the middle and a single while (fast.next!=null&&fast.next.next! =null) { fast=fast.next.next; Leftofmid=slow; Slow=slow.next; } if (leftofmid==null)//description does not enter the upper while loop indicates that there is only 1 or two nodes at this time there is no left-linked list of the left half of the Head=null; else leftofmid.next=null;//If there is a left half of the list to the left, the end of the link is empty, the list is truncated to two segments ListNode the beginning of the right half of the rightofmid=slow.next;//list TreeNode root=new TreeNode (slow.val); Root.left=sortedlisttobst (head); Root.right=sortedlisttobst (rightofmid); return root; }
The above time complex area is N*logn, there is no O (n) algorithm, the new tree node time complexity is O (n), so in the search for the middle node can only be a constant time, so that the final time complexity of O (n), so that only with the help of a hash table
Code:
With hash table O (n) time complexity public static TreeNode sortedListToBST2 (ListNode head) { hashtable< Integer, treenode> Hashtable=new hashtable<> (); if (head==null) return null; ListNode Cur=head; int length=0; while (Cur!=null) { TreeNode node=new TreeNode (cur.val); Hashtable.put (Length,node); Cur=cur.next; length++; } Return Buildtree (0, Length-1, Hashtable); } public static TreeNode buildtree (int start,int end,hashtable<integer, treenode> Hashtable) { if (start<= End) { int mid= (start+end)/2; TreeNode Root=hashtable.get (mid); Root.left=buildtree (Start,mid-1, Hashtable); Root.right=buildtree (mid+1, End, Hashtable); return root; } else {return null;} }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode109_convert Sorted List to binary Search T topic titree (Turn linked list to binary sort tree) Java puzzle