109-convert Sorted list to binary Search tree (sort list converted to binary sort tree)
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory 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 to a highly balanced two-fork tree
Thinking of solving problems
Solution One: The value of the single-linked list into an array, through the array to build a binary tree, the algorithm time complexity is: O (n), the spatial complexity is: O (n)
Solution Two: The recursive method is used,
(a) Find the middle node, 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
The second method of solving 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); }//Fast moving 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);//re-connect the linked list.Mid.next = Midnext;//Return results returnRoot }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47393027"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java Implementation" "109-convert Sorted List to Binary Search tree (sort list converted to binary sort tree)"