1099. Build A Binary Search Tree (30)

原创 2016年08月29日 14:39:45
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
int n;
vector <int> ans;
struct node
{
	int lchild,rchild;
	int num;
}nodes[105];
int f(int x)
{
	if(x==-1)
	return 0;
	return f(nodes[x].lchild)+f(nodes[x].rchild)+1;
}
void build(int r,int L,int R)
{
	if(r==-1)
	return;
	int n=f(nodes[r].lchild);
	nodes[r].num=ans[L+n];
	build(nodes[r].lchild,L,L+n-1);
	build(nodes[r].rchild,L+n+1,R);
}
int main()
{
	cin>>n;
	for(int i=0;i<n;i++)
	cin>>nodes[i].lchild>>nodes[i].rchild;
	ans.resize(n);
	for(int i=0;i<n;i++)
	cin>>ans[i];
	sort(ans.begin(),ans.end());
	build(0,0,n-1);
	//for(int i=0;i<n;i++)
	//cout<<nodes[i].num<<endl;
	bool flag=false;
	queue <int> que;
	que.push(0);
	while(!que.empty())
	{
		int tmp=que.front();
		if(flag)
		{
			cout<<' '<<nodes[tmp].num;
		}
		else 
		{
			cout<<nodes[tmp].num;
			flag=1;
		}
		que.pop();
		if(nodes[tmp].lchild!=-1)
		{
			que.push(nodes[tmp].lchild);
		}
		if(nodes[tmp].rchild!=-1)
		{
			que.push(nodes[tmp].rchild);
		}
	}
	return 0;
} 

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

1099. Build A Binary Search Tree (30)

先递归恢复树的形状,然后对数列排序,中序遍历树,按顺序把关键字插入树中。最后层序遍历整棵树。 #define _CRT_SECURE_NO_WARNINGS #include #inclu...

PAT 1099. Build A Binary Search Tree (30)

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following propertie...

pat 1099. Build A Binary Search Tree (30)

1099. Build A Binary Search Tree (30) 时间限制 100 ms 内存限制 65536 kB 代码长度限...

PAT - 甲级 - 1099. Build A Binary Search Tree (30)(二叉搜索树+层次遍历+中序遍历)

题目描述: A Binary Search Tree (BST) is recursively defined as a binary tree which has the following ...

1099. Build A Binary Search Tree (30)

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following propertie...

【PAT】1099. Build A Binary Search Tree (30)

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following propertie...

PAT A1099. Build A Binary Search Tree (30)

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following propertie...

PAT (Advanced Level) Practise 1099 Build A Binary Search Tree (30)

1099. Build A Binary Search Tree (30) 时间限制 100 ms 内存限制 65536 kB 代码长度限...

1099. Build A Binary Search Tree (30)

1.这道题目难度不大,主要思想如下: 1)先构建二叉树(此时尚未填值) 2)输出二叉树的中序遍历地址 3)对数组进行排序 4)把数组的数输入到中序遍历地址相应的节点值中 AC代码: ...

PAT (Advanced Level) 1099. Build A Binary Search Tree (30) 中序遍历往BST中填数据

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following propertie...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)