Look at the problem, the first thought of the solution is as follows:
(1) A single function can be designed to calculate the precursor node of the intermediate node of the ordered list . The following will see the reason that this function enters the ordered list length of at least 2 nodes;
(2 ) Back to the function you originally wanted to design:
A. If no node returns NULL, if there is only one node, the node is made into a tree node to return; for this reason, an ordered list of at least 2 nodes is entered into the problem of finding the precursor node;
B. Locate the precursor node, locate the intermediate node, and complete the assignment.
c. cutting segments between the precursor node and the intermediate node; for the purpose of realizing the recursive use of divide and conquer;
D. Recursive search for left node, right node, return root node;
Where: A separate design function is worth mentioning because: 2/2 = 1, 3/2 = 1; 4/2 = 2, 5/2 = 2; ~ ~ ~ at the time of integer division;
Therefore, the search for the precursor function of the loop design, need to say all the circumstances of the Statute into a pair of odd a group of appearance, and, because the starting point is 2, so every time is even in front, odd in the back;
Public classSolution {ListNode getleftnodefromlist (ListNode head) {//By default, there are at least 2 linked list nodesListNode next =Head.next; ListNode Index=Head.next; ListNode Pre=Head; while(Next! =NULL) {Next=Next.next; if(Next = =NULL) Break; Next=Next.next; if(Next = =NULL) Break; Pre=Pre.next; Index=Pre.next; } returnPre; } PublicTreeNode Sortedlisttobst (ListNode head) {if(Head = =NULL)return NULL; if(Head.next = =NULL)return NewTreeNode (Head.val); ListNode Left=Getleftnodefromlist (head); ListNode Mid=Left.next; Left.next=NULL; TreeNode Root=NewTreeNode (Mid.val); Root.left=Sortedlisttobst (head); Root.right=Sortedlisttobst (Mid.next); returnRoot; }}
Of course, this is not the best approach, and we'll discuss the optimal solution later, which is based on recursion and time complexity: O (N*LGN)
109. Convert Sorted list to Binary Search Tree transforms an ordered list into BST