1099 Build A Binary Search Tree (30 分)(二叉查詢樹BST)
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
題目大意:
給出一棵二叉搜尋樹(給出每個結點的左右孩子),且已知根結點為0,求並且給出應該插入這個二叉搜尋樹的數值,求這棵二叉樹的層序遍歷
分析:
- 用結構體data,left,right表示這棵樹的結構,a陣列存樹的資訊,b陣列存這棵樹節點的所有data,根據輸入可知樹a[i]的left和right~
- 因為是二叉搜尋樹,所以中序遍歷這棵樹得到的結點順序應該是給出的數值序列從小到大的排列順序,所以把數值序列排序後,可以在中序遍歷的時候直接賦值當前a[root].data~同時可得知樹的最大層數maxLevel的值~
- 二維陣列v用來儲存每一層的結點下標,一共有0到maxLevel層。用for迴圈從0開始一層層遍歷v,就可以得到下一層的l和r,遍歷過程中可以輸出每個結點對應的data值a[v[i][j]].data~
原文連結:https://blog.csdn.net/liuchuo/article/details/52181651
題解
#include <bits/stdc++.h>
using namespace std;
const int maxn=110;
struct node
{
int data;
int lchild,rchild;
}Node[maxn];
int n,in[maxn],num=0;
void inOrder(int root)
{
if(root==-1) return;
inOrder(Node[root].lchild);
Node[root].data=in[num++];
inOrder(Node[root].rchild);
}
void BFS(int root)
{
queue<int> q;
q.push(root);
num=0;
while(!q.empty()){
int now=q.front();
q.pop();
cout<<Node[now].data;
num++;
if(num<n) cout<<" ";
if(Node[now].lchild!=-1) q.push(Node[now].lchild);
if(Node[now].rchild!=-1) q.push(Node[now].rchild);
}
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif
int lchild,rchild;
cin>>n;
for(int i=0;i<n;i++){
cin>>lchild>>rchild;
Node[i].lchild=lchild;
Node[i].rchild=rchild;
}
for(int i=0;i<n;i++){
cin>>in[i];
}
sort(in,in+n);
inOrder(0);
BFS(0);
return 0;
}
本文來自部落格園,作者:勇往直前的力量,轉載請註明原文連結:https://www.cnblogs.com/moonlight1999/p/15768424.html