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:
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.构建二叉树,中序遍历二叉树,确定中序遍历二叉树的节点序列; 2.对数字排序,因为中序遍历二叉树的得到的是升序的数字, 所以按照中序遍历得到的节点序列,把排序后的数字依次填入节点; 3.层序遍历二叉树,输出结果
1 #include<iostream> 2 #include<vector> 3 #include<queue> 4 #include<algorithm> 5 using namespace std; 6 vector<int> v(100), tree[100], ans(100), temp, out; 7 void dfs(int node){ 8 if(tree[node][0]!=-1) dfs(tree[node][0]); 9 temp.push_back(node); 10 if(tree[node][1]!=-1) dfs(tree[node][1]); 11 } 12 int main(){ 13 int n, i; 14 cin>>n; 15 for(i=0; i<n; i++){ 16 int a, b; 17 cin>>a>>b; 18 tree[i].push_back(a); tree[i].push_back(b); 19 } 20 for(i=0; i<n; i++) cin>>v[i]; 21 sort(v.begin(), v.begin()+n); 22 dfs(0); 23 for(i=0; i<n; i++) ans[temp[i]] = v[i]; 24 queue<int> q; 25 q.push(0); 26 while(q.size()){ 27 int tempnode=q.front(); 28 q.pop(); 29 out.push_back(ans[tempnode]); 30 if(tree[tempnode][0]!=-1) q.push(tree[tempnode][0]); 31 if(tree[tempnode][1]!=-1) q.push(tree[tempnode][1]); 32 } 33 for(i=0; i<n; i++){ 34 if(i==0) cout<<out[i]; 35 else cout<<" "<<out[i]; 36 } 37 cout<<endl; 38 return 0; 39 }