Tree Construction
problem ' s Link
----------------------------------------------------------------------------
Mean:
Given the number of N, the BST tree is constructed in the same way that binary Search tree is constructed, sequentially outputting the value of each non-root node's parent.
Analyse:
Constructing the BST tree with a worst-case time complexity of O (n) will definitely time out.
Notice that only the value of the parent node of the output node is required, and the BST tree does not need to be constructed.
When inserting the first node, we find two numbers in the first i-1 node, one is the smallest number larger than AI, and the largest number is smaller than AI.
Then the parent of the AI is definitely one of these two, which one, according to the drawing analysis, can be derived from the later inserted.
As shown in the following:
Practice: Use the container treemap<integer,integer> in Java to store <value,index> pair, find according to value values, and then compare the index size of these two numbers to determine who is the parent node.
Time complexity:o (N*LOGN)
View Code
1. Using the Java Container implementationImport Java.io.BufferedInputStream;
Import Java.util.HashMap;
Import Java.util.Scanner;
Import Java.util.TreeSet;
Public class Main{
Public Static void Main(String[]argv){
Scanner inch=New Scanner(New Bufferedinputstream(System.inch));
while(inch.Hasnext()){
intN=inch.Nextint();
TreeSet<Integer> Vals=New TreeSet<> ();
HashMap<Integer,Integer> idx=New HashMap<> ();
int Val=inch.Nextint();
Vals.Add(Val);
idx.put(Val,0);
for(int I=1;I<N;++I){
Val=inch.Nextint();
Integer Hi=Vals.Higher(Val), Lo=Vals.Lower(Val);
if(Hi==NULL)
System. out.Print(Lo+" ");
Else if(Lo==NULL)
System. out.Print(Hi+" ");
Else {
Integer Hiidx=idx.Get(Hi);
Integer Loidx=idx.Get(Lo);
if(Hiidx>Loidx)
System. out.Print(Hi+" ");
Else
System. out.Print(Lo+" ");
}
Vals.Add(Val);
idx.put(Val,I);
}
System. out.println();
}
}
}
2. Segment Tree Implementation
Data Structures-Codeforces Round #353 (Div. 2) D. Tree Construction