Problem description
For an ordered array or linked list, there are often multiple approaches to converting to a relatively balanced BST tree.
1. For an ordered array A, to BST, take the middle element of the array a[m], to the root, and then recursively convert a[1..m-1], a[m+1. N]. Time complexity t (n) = 2 * t (N/2) + O (1), resulting t (n) = O (n)
2. For the orderly chain list, if the above method, also can be carried out. However, to get to a[m], you need to traverse an array of N/2 lengths, so extra O (n) time is required to fetch A[M]. So the time complexity is t (n) = 2 * t (N/2) + O (n), which results in t (n) = n log (n).
OK, the question comes, if you want to make the ordered list to BST is also O (n) time, how to deal with it?
Solution Solutions
For the problem of ordered list, we can solve it by referring to the recursive scheme. The difference is that when the left half is recursive, the head node of the single linked list is updated simultaneously.
Linknode *head as a parameter input, when the conversion is complete, the head becomes the tail node of the single-linked list->next, which is null. When a Linknode node is processed each time, the head moves to the same node right. The following are the specific examples:
#include <iostream>#include <cstdio>#include <cstdlib>#include <algorithm>#include <vector>#include <cstring>using namespace STD;//node structure of single linked liststructLinknode {intValue Linknode *next; Linknode (intV): Value (v), next (NULL) {}};//BST node structurestructBstnode {intValue Bstnode *left, *right; Bstnode (intV): Value (v), left (null), right (null) {}};classSolution { Public:voidSolve () {//Test case intArr[] = {1,2,3,4,5,6,7}; Linknode *head = null, *p = NULL; for(inti =0; I <sizeof(arr)/sizeof(int); i++) {if(head = = NULL) head = p =NewLinknode (Arr[i]);ElseP->next =NewLinknode (Arr[i]), p = p->next; } Bstnode *root = Convert (head,0,sizeof(arr)/sizeof(int)-1); Printbstnode (root);printf("\ n"); }//move ahead the head pointer when carrying out the inorder traversal. //In the This, we avoid N*log (n) Time complexityBstnode *convert (Linknode *&head,intSinte) {Bstnode *root = NULL;if(S > E) { }Else if(s = = e) {root =NewBstnode (Head->value); Head = head->next; }Else{intm = s + (e-s)/2; Bstnode *left = Convert (head, S, M1); Root =NewBstnode (Head->value); Head = head->next; Bstnode *right = Convert (head, m+1, e); Root->left = left; Root->right = right; }returnRoot }//For printing out the content of a bstnode tree, inorder printing voidPrintbstnode (Bstnode *root) {if(Root = NULL)return; Printbstnode (Root->left);printf("%d", Root->value); Printbstnode (Root->right); }};intMain () {solution solution; Solution.solve ();}
Ordered single-linked table to BST tree + time Complexity requirements O (n)