PAT.A1099 Build A Binary Search Tree

Back to Contents

Insert picture description hereInsert picture description here

Title

The binary tree has N nodes (node ​​numbers 0 ~ N-1), and gives the number of the left and right child nodes of each node (there is no -1). Next, a sequence of N integers is given. The N integers need to be filled into the nodes of the binary tree, so that the binary tree becomes a binary search tree. Output the sequence traversal sequence of this binary search tree.

Sample (can be copied)

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
//output
58 25 82 11 38 67 45 73 42

important point

  1. Because the title directly gives the relationship of the node number, it is more convenient to use the static writing method of the binary tree.
  2. For a binary search tree, the mid-order traversal sequence is incremental, so you only need to sort the given integer sequence from small to large, and then perform the mid-order traversal of the given binary tree, and sort the integers of the sorted sequence by The order of traversal in the middle order is filled into the binary tree to form a binary search tree.
  3. The root node defaults to 0
#include<bits/stdc++.h>
using namespace std;

int n,lc,rc,data[110],pos=0;
struct Node{
	int data,lc,rc;
}node[110]; 
void ininsert(int root){
	if(root==-1)return;
	ininsert(node[root].lc);
	node[root].data=data[pos++];
	ininsert(node[root].rc);
}
void BFS(int root){
	queue<int> q;
	q.push(root);
	int num=0;
	while(!q.empty()){
		int now=q.front();
		q.pop();
		printf("%d",node[now].data);
		num++;
		if(num<n)printf(" ");
		if(node[now].lc!=-1)q.push(node[now].lc);
		if(node[now].rc!=-1)q.push(node[now].rc);
	}
}
int main(){
	cin>>n;
	for(int i=0;i<n;i++){
		scanf("%d%d",&lc,&rc);
		node[i].lc=lc;
		node[i].rc=rc;
	}
	for(int i=0;i<n;i++)scanf("%d",&data[i]);
	sort(data,data+n);
	ininsert(0);//中序遍历插入元素
	BFS(0)//层次遍历
    return 0;
}
Published 177 original articles · praised 5 · visits 6661

Guess you like

Origin blog.csdn.net/a1920993165/article/details/105516363
Recommended