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的规则填进去,最后按照Level order输出这些数。
我的做法是首先把输入的N个数排序,然后对每个节点DFS求出左子树总节点数和右子树总节点数,然后递归的填入数据。
最后再用BFS遍历整棵树并输出数据即可。 代码如下:
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
using namespace std;
typedef struct node{
int level;
int leftchild;
int rightchild;
int leftcount;
int rightcount;
int element;
node(){
leftcount=0;
rightcount=0;
level=0;
}
}node;
vector<node> raw;
vector<int> num;
queue<int> sequence;
int dfs(int x)
{
if(x==-1)
return 0;
raw[x].leftcount=dfs(raw[x].leftchild);
raw[x].rightcount=dfs(raw[x].rightchild);
return raw[x].leftcount+raw[x].rightcount+1;
}
void bfs(int x)
{
queue<node> myqueue;
myqueue.push(raw[x]);
cout<<raw[x].element;
while(myqueue.size())
{
node temp=myqueue.front();
myqueue.pop();
if(temp.leftchild!=-1)
{
cout<<" "<<raw[temp.leftchild].element;
myqueue.push(raw[temp.leftchild]);
}
if(temp.rightchild!=-1)
{
cout<<" "<<raw[temp.rightchild].element;
myqueue.push(raw[temp.rightchild]);
}
}
}
void fillin(int x,int begin,int end)
{
if(begin>end)
return;
int pos=end-raw[x].rightcount;
fillin(raw[x].rightchild,pos+1,end);
fillin(raw[x].leftchild,begin,pos-1);
raw[x].element=num[pos];
}
int main(void)
{
int i,j,N;
cin>>N;
for(i=0;i<N;i++)
{
node temp;
cin>>temp.leftchild>>temp.rightchild;
raw.push_back(temp);
}
num.resize(N);
for(i=0;i<N;i++)
cin>>num[i];
sort(num.begin(),num.end());
dfs(0);
fillin(0,0,N-1);
bfs(0);
}