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
题目大意:给出一个BST的每个结点的左右孩子结点的编号,不存在就是-1;接着给出每个节点对应的数据data,让我们根据这些信息给出此树的层序遍历。
BST的特点:中序遍历是有序的,因此我们可以先对这些数据从小到大排序,然后进行中序遍历,对应节点赋值,这样就完成了此BST,最后在进行层序遍历就好了。
注意事项:
1、在保存层序遍历的值时,刚开始用了vector,提交上去提示我内存超过了上限,后面改成数组才通过。
2、在层序遍历时老是犯了一个错:push进去的经常是根节点的左右节点,没有更新。一定要注意参数。
#include <iostream>
#include "algorithm"
#include "queue"
#include "vector"
using namespace std;
const int maxx = 110;
int in[maxx],j=0,k=0;
int level[maxx];
struct node{
int data;
int left=-1,right=-1;
}Node[maxx];
void inorder(int root){
if (root==-1) return;
inorder(Node[root].left);
Node[root].data = in[j++];
inorder(Node[root].right);
}
void levelorder(int root){
queue<int> m;
m.push(root);
while (!m.empty()){
int top = m.front();
level[k++]=Node[top].data;
m.pop();
if (Node[top].left != -1) m.push(Node[top].left);
if (Node[top].right != -1) m.push(Node[top].right);
}
}
int main() {
int m;
scanf("%d",&m);
int a,b,temp;
for (int i = 0; i < m; ++i) {
cin>>a>>b;
Node[i].left=a;
Node[i].right = b;
}
for (int i = 0; i < m; ++i) {
cin>>in[i];
}
sort(in,in+m);
inorder(0);
levelorder(0);
for (int i = 0; i < m; ++i) {
if (i == 0) printf("%d",level[i]);
else printf(" %d",level[i]);
}
}