1099 Build A Binary Search Tree (30)

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, tree[100], ans(100), in,  level;
 7 void inOrder(int node){
 8   if(tree[node][0]!=-1)inOrder(tree[node][0]);
 9   in.push_back(node);
10   if(tree[node][1]!=-1) inOrder(tree[node][1]);
11 }
12 int main(){
13   int n, i;
14   scanf("%d", &n);
15   v.resize(n);
16   for(i=0; i<n; i++){
17     int a, b;
18     scanf("%d%d", &a, &b);
19     tree[i].push_back(a); tree[i].push_back(b);
20   }
21   for(i=0; i<n; i++) scanf("%d", &v[i]);
22   sort(v.begin(), v.end());
23   inOrder(0);
24   //把节点的值填入节点中
25   for(i=0; i<n; i++) ans[in[i]] = v[i];
26   queue<int> q;
27   q.push(0);
28   while(q.size()){//程序遍历
29     int tempnode=q.front();
30     q.pop();
31     level.push_back(ans[tempnode]);
32     if(tree[tempnode][0]!=-1) q.push(tree[tempnode][0]);
33     if(tree[tempnode][1]!=-1) q.push(tree[tempnode][1]);
34   }
35   for(i=0; i<n; i++){
36     if(i==0) printf("%d", level[i]);
37     else printf(" %d", level[i]);
38   }
39   
40   return 0;
41 }

 

posted @ 2018-06-14 10:12  赖兴宇  阅读(157)  评论(0编辑  收藏  举报