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 (≤) 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 − 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:
9
1 6
2 3
-1 -1
-1 4
5 -1
-1 -1
7 -1
-1 8
-1 -1
73 45 11 58 82 25 67 38 42
Sample Output:
58 25 82 11 38 67 45 73 42
1 #include <iostream> 2 #include <queue> 3 #include <vector> 4 #include <algorithm> 5 using namespace std; 6 struct Node 7 { 8 int val, l, r; 9 }node[105]; 10 vector<int>nums(105), levelOrder; 11 int N, k = 0; 12 void inOrderTravel(int root)//得到树的中序遍历 13 { 14 if (root == -1) 15 return; 16 inOrderTravel(node[root].l); 17 node[root].val = nums[k++]; 18 inOrderTravel(node[root].r); 19 } 20 void levelOrderTravel(int root)//得到树的中序遍历 21 { 22 queue<int>q; 23 q.push(root); 24 while (!q.empty()) 25 { 26 root = q.front(); 27 q.pop(); 28 levelOrder.push_back(node[root].val); 29 if (node[root].l != -1) 30 q.push(node[root].l); 31 if (node[root].r != -1) 32 q.push(node[root].r); 33 } 34 } 35 int main() 36 { 37 cin >> N; 38 int l, r; 39 int root = 0; 40 for (int i = 0; i < N; ++i)//按题目意思使用前序遍历构建一棵树 41 { 42 cin >> l >> r; 43 node[i].l = l; 44 node[i].r = r; 45 } 46 for (int i = 0; i < N; ++i) 47 cin >> nums[i]; 48 sort(nums.begin(), nums.begin() + N);//得到中序遍历 49 inOrderTravel(root);//通过中序遍历重构二叉树 50 levelOrderTravel(root); 51 for (int i = 0; i < N; ++i) 52 cout << levelOrder[i] << (i == N - 1 ? "" : " "); 53 return 0; 54 }