109-convert Sorted list to binary Search tree (sort list converted to binary sort tree)
"leetcode-Interview algorithm classic-java Implementation" "All Topics folder Index"
Original Question
Given a singly linked list where elements is sorted in ascending order, convert it to a height balanced BST.
Main Topic
Given an ascending single-linked list. Convert it into a highly balanced two-fork tree
Thinking of solving problems
Solution One: The values in the single-linked list are stored in an array, and the binary tree is constructed by an array. Algorithm time complexity is: O (n), spatial complexity is: O (n)
Solution Two: Adopt the way of recursion.
(a) Find the middle node and build the root node.
(ii) the left half of the middle node constructs the left sub-tree,
(iii) Right sub-tree of middle node construction
Another solution to the problem
Code Implementation
Tree Node class
publicclass TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }}
Algorithm implementation class
Public classSolution { PublicTreeNodeSortedlisttobst(ListNode head) {//If the list is empty, return null directly if(Head = =NULL) {return NULL; }//list has only one node. if(Head.next = =NULL) {return NewTreeNode (Head.val); }//high-speed mobile nodes, two positions per moveListNode fast = Head.next.next;//Record intermediate nodesListNode mid = head;//Find the middle node. while(Fast! =NULL&& Fast.next! =NULL) {mid = Mid.next; Fast = Fast.next.next; }//With the next node of the middle node as the root node .TreeNode root =NewTreeNode (Mid.next.val);//Build Right sub-treeRoot.right = Sortedlisttobst (Mid.next.next);//Record list of points to be brokenListNode midnext = Mid.next;//Disconnect single-linked list (destroys the structure of the original single-linked list)Mid.next =NULL;//Build left subtreeRoot.left = Sortedlisttobst (head);//Once again, connect the linked list.Mid.next = Midnext;//Return results returnRoot }}
Assessment Results
Click on the picture, the mouse does not release. Drag a section of the position. After release, view the full picture in the new form.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47393027"
"Leetcode-Interview algorithm classic-java Implementation" "109-convert Sorted List to Binary Search tree (sort list converted to binary sort tree)"