A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
- Both the left and right subtrees must also be binary search trees.
Given the structure of a binary tree and a sequence of distinct integer keys, there is only one way to fill these keys into the tree so that the resulting tree satisfies the definition of a BST. You are supposed to output the level order traversal sequence of that tree. The sample is illustrated by Figure 1 and 2.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (<=100) which is the total number of nodes in the tree. The next N lines each contains the left and the right children of a node in the format "left_index right_index", provided that the nodes are numbered from 0 to N-1, and 0 is always the root. If one child is missing, then -1 will represent the NULL child pointer. Finally N distinct integer keys are given in the last line.
Output Specification:
For each test case, print in one line the level order traversal sequence of that tree. All the numbers must be separated by a space, with no extra space at the end of the line.
Sample Input:
91 62 3-1 -1-1 45 -1-1 -17 -1-1 8-1 -173 45 11 58 82 25 67 38 42
Sample Output:
58 25 82 11 38 67 45 73 42
1 #include2 #include 3 #include 4 #include 5 #include 6 #include 7 using namespace std; 8 9 struct node10 {11 int l,r,v;12 };13 14 node Tree[110];15 vector vv;16 int cnt = 0;17 void inOder(int root)18 {19 if(Tree[root].l != -1)20 inOder(Tree[root].l);21 Tree[root].v = vv[cnt++];22 if(Tree[root].r != -1)23 inOder(Tree[root].r);24 }25 26 int main()27 {28 int n,tem;29 scanf("%d",&n);30 for(int i = 0 ;i < n;++i)31 {32 scanf("%d%d",&Tree[i].l,&Tree[i].r);33 }34 35 for(int i = 0 ;i < n;++i)36 {37 scanf("%d",&tem);38 vv.push_back(tem);39 }40 sort(vv.begin(),vv.end());41 inOder(0);42 queue qq;43 qq.push(Tree[0]);44 bool fir = 1;45 while(!qq.empty())46 {47 node ntem = qq.front();48 qq.pop();49 if(fir)50 {51 fir = 0;52 printf("%d",ntem.v);53 }54 else55 {56 printf(" %d",ntem.v);57 }58 if(ntem.l != -1)59 qq.push(Tree[ntem.l]);60 if(ntem.r != -1)61 qq.push(Tree[ntem.r]);62 }63 printf("\n");64 return 0;65 }