For the convert Sorted array to binary Search tree, it is relatively simple to use a two-point method to determine the extent of the left and right trees.
For this problem, it is possible to use a binary method, but there is no random access to the array of attributes, it is necessary to traverse the array to find the middle node of the list. To make it easier to find the middle node, you can first count the number of nodes.
The rest of the process changed to
Level 1: Traversal of N/2 nodes
Level 2: Traversing N/4,N/4 points of achievement
Level 3: Traversal of N/8,N/8,N/8,N/8 nodes
So the total number of traversal nodes is: N/2*log (N)
So the complexity is O (Nlog (N))
The method above can be recursive, with a recursive depth of log (N)
Second, using the idea of the middle sequence traversal, as well as the monotonic order of the final required traversal of BST itself, can design another method.
The general idea is: The final traversal of the simulated binary search tree, using two values left and right to delimit the range, if left>right, returns NULL. otherwise traverse [left,mid-1] and [mid+1,right] respectively
Using the characteristics of the middle sequence traversal, after the left tree traversal, after the current root node is initialized, and will point to the next node, at the next initialization, see exactly the end must traverse the next node.
1ListNode current=NULL;2 PrivateTreeNode Indfs (intLeftintRight ) {3 if(Right<left)return NULL;4TreeNode Lefttree = Indfs (left, (left+right)/2-1);5TreeNode root =NewTreeNode (current.val);6Current=Current.next;7TreeNode Righttree = Indfs ((left+right)/2+1, right);8Root.left =Lefttree;9Root.right =Righttree;Ten returnRoot; One } A - PublicTreeNode Sortedlisttobst (ListNode h) { - intCount=0; theListNode tmp=h; - while(tmp!=NULL){ -count++; -tmp=Tmp.next; + } - if(h==NULL)return NULL; +Current =h; A returnIndfs (0, count-1); at}
[Leetcode] Convert Sorted List to Binary Search Tree