Enter an ordered array, how do you put this ordered array of integers into a two-fork tree?
Analysis: For binary tree, this ordered array can be inserted into the two-fork search tree, after all, the binary search tree is still a lot of specific. So for the creation of a two-fork search tree, it is simply recursive. The algorithm design of the tree must be associated with recursion, because the tree itself is a recursive function.
Then for this ordered array analysis, the median of this array as the root node, and then for the first half of the array to create a tree as the root node of the left subtree, the second half to create a binary search tree as the right subtree of the root node. So that's the recursive call.
#include <iostream> #include <vector>using namespace std;/* efficiently inserts an ordered array into the two-search tree */typedef struct BIN_TREE bintree;struct bin_tree{ int value; bintree* right; bintree* left;}; void Insertfromarray (bintree*& root,int* array,int start,int end) { if (start >end) return; root = new Bintree; Root->left = NULL; Root->right = NULL; int mid = start+ (End-start)/2; Root->value = Array[mid]; Insertfromarray (root->left,array,start,mid-1); Insertfromarray (root->right,array,mid+1,end); } /* Recursive middle sequence traversal binary tree */void inorder (bintree* root) { if (root = NULL) return; Inorder (root->left); cout<<root->value<<endl; Inorder (root->right);} int main () { int array[]={1,2,3,4,5,6,7,8,9}; bintree* root =null; Insertfromarray (root,array,0,8); Inorder (root); System ("pause"); return 0; }
In the interview questions, there are similar questions, how to 100w some of the data into the map in the STL, the first is to judge the bottom of the map implementation is a red black tree, is a more special two-fork search tree, you can also use the above method to insert, but it is important to note that After all, the red and black tree is not exactly the same as the two-fork search tree, which can cause color changes after insertion.
How to quickly insert an ordered array into a binary tree