[C++] PAT Build A Binary Search Tree (30分)

在这里插入图片描述

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

题解:

在二叉搜索树中,对其进行中序遍历的结果是给出的数值序列从小到大的排列顺序,利用该该特性,以中序遍历方式构建二叉树的同时为节点赋值,最后再进行一次层次遍历即可

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>

using namespace std;

struct node{
	int v;
	node* left;
	node* right;
};

int b[110][2];
int arr[110];
int n;
int index = 0;

bool cmp(int a,int b){
	return a < b;
}

void create(node* &root,int ind){
	root = new node();
	if(b[ind][0] != -1){
		create(root->left,b[ind][0]);
	}
	root->v = arr[index++];
	if(b[ind][1] != -1){
		create(root->right,b[ind][1]);
	}
}

void bfs(node* root){
	queue<node*> q;
	q.push(root);
	while(!q.empty()){
		node* temp = q.front();
		q.pop();
		if(temp->left != NULL){
			q.push(temp->left);
		}
		if(temp->right != NULL){
			q.push(temp->right);
		}
		cout << temp->v; 
		if(!q.empty()){
			cout << " "; 
		}
	}
}
int main(){
	cin >> n;
	for(int i=0;i<n;i++){
		scanf_s("%d %d",&b[i][0],&b[i][1]);
	}
	for(int i=0;i<n;i++){
		scanf_s("%d",&arr[i]);
	}
	sort(arr,arr+n,cmp);
	node* root = new node();
	create(root,0);
	bfs(root);
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值