二叉树层序遍历,Trees on the level UVA - 122——紫书第六章例题和字符串新解

这篇博客探讨了二叉树在计算机科学中的重要性,特别是在并行计算和图形算法中的应用。文章介绍了如何通过输入的一系列节点值和路径来构建二叉树,并使用层次遍历的方法进行节点的顺序打印。程序实现包括三种不同的数据结构:链表、数组和内存池,每种方法都确保了在不超过256个节点的限制下正确地遍历二叉树。同时,文章指出如果树不完全指定或者节点值重复,将输出'notcomplete'。
摘要由CSDN通过智能技术生成

https://vjudge.net/problem/UVA-122

Trees are fundamental in many branches of computer science (Pun definitely intended). Current stateof-the art parallel computers such as Thinking Machines’ CM-5 are based on fat trees. Quad- and
octal-trees are fundamental to many algorithms in computer graphics.
This problem involves building and traversing binary trees.
Given a sequence of binary trees, you are to write a program that prints a level-order traversal of each tree. In this
problem each node of a binary tree contains a positive integer
and all binary trees have have fewer than 256 nodes.
In a level-order traversal of a tree, the data in all nodes at
a given level are printed in left-to-right order and all nodes at
level k are printed before all nodes at level k + 1.
For example, a level order traversal of the tree on the right
is: 5, 4, 8, 11, 13, 4, 7, 2, 1.
In this problem a binary tree is specified by a sequence
of pairs ‘(n,s)’ where n is the value at the node whose path
from the root is given by the string s. A path is given be
a sequence of ‘L’s and ‘R’s where ‘L’ indicates a left branch and ‘R’ indicates a right branch. In the
tree diagrammed above, the node containing 13 is specified by (13,RL), and the node containing 2 is
specified by (2,LLR). The root node is specified by (5,) where the empty string indicates the path from
the root to itself. A binary tree is considered to be completely specified if every node on all root-to-node
paths in the tree is given a value exactly once.
Input
The input is a sequence of binary trees specified as described above. Each tree in a sequence consists
of several pairs ‘(n,s)’ as described above separated by whitespace. The last entry in each tree is ‘()’.
No whitespace appears between left and right parentheses.
All nodes contain a positive integer. Every tree in the input will consist of at least one node and
no more than 256 nodes. Input is terminated by end-of-file.
Output
For each completely specified binary tree in the input file, the level order traversal of that tree should
be printed. If a tree is not completely specified, i.e., some node in the tree is NOT given a value or a
node is given a value more than once, then the string ‘not complete’ should be printed.
Sample Input
(11,LL) (7,LLL) (8,R)
(5,) (4,L) (13,RL) (2,LLR) (1,RRR) (4,RR) ()
(3,L) (4,R) ()
Sample Output
5 4 8 11 13 4 7 2 1
not complete

好多方法!

  1. 链表
//#pragma GCC optimize(3,"Ofast","inline")
//#pragma GCC optimize(2)
#include<stdio.h>
#include<string.h>
#include<queue>
#ifdef LOCAL
FILE*FP=freopen("text.in","r",stdin);
//FILE*fp=freopen("text.out","w",stdout);
#endif
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
#define _forplus(i,a,b) for( register int i=(a); i<=(b); i++)
#define forplus(i,a,b) for( register int i=(a); i<(b); i++)
#define _forsub(i,a,b) for( register int i=(a); i>=(b); i--)
#define _forauto(a,b) for(auto &(a):(b))
#define pb push_back
#define N 258
char s[N];
struct Node{
	bool have_value;
	int v;
	Node *left,*right;
	Node():have_value(false),left(NULL),right(NULL){}
};
Node * root;
bool failed;
#define newnode()  new Node()
#define search(a) if(u->a==NULL)u->a=newnode();u=u->a
void addnode(int v,char*s){
	int n=strlen(s);
	Node* u=root;
	forplus(i,0,n){
		if(s[i]=='L'){
			search(left);
		}else if(s[i]=='R'){
			search(right);
		}
	}
	if(u->have_value)failed=true;
	u->v=v;
	u->have_value=true;
}
bool read_input(){
	failed=false;
	root=newnode();
	for(;;){
		if(scanf("%s",s)!=1)return false;
		if(!strcmp(s,"()"))break;
		int v;
		sscanf(&s[1],"%d",&v);
		addnode(v,strchr(s,',')+1);
	}
	return true;
} 
#define qp(a) if(u->a!=NULL)q.push(u->a);
bool bfs(vector<int>&ans){
	queue<Node*>q;
	ans.clear();
	q.push(root);
	while(!q.empty()){
		Node*u=q.front();q.pop();
		if(!u->have_value)return false;
		ans.pb(u->v);
		qp(left);
		qp(right);
	}
	return true;
}
int main(){
	while(read_input()){
		vector<int> ans;
		if(failed==false&&bfs(ans)){
			int flag=0;
			_forauto(i,ans){
				flag?putchar(' '):flag=1;
				printf("%d",i);
			}
			printf("\n");
		}else{
			printf("not complete\n");
		} 
	}
	return 0;
}

  1. 数组
//#pragma GCC optimize(3,"Ofast","inline")
//#pragma GCC optimize(2)
#include<stdio.h>
#include<string.h>
#include<queue>
#ifdef LOCAL
FILE*FP=freopen("text.in","r",stdin);
//FILE*fp=freopen("text.out","w",stdout);
#endif
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
#define _forplus(i,a,b) for( register int i=(a); i<=(b); i++)
#define forplus(i,a,b) for( register int i=(a); i<(b); i++)
#define _forsub(i,a,b) for( register int i=(a); i>=(b); i--)
#define _forauto(a,b) for(auto &(a):(b))
#define pb push_back
#define N 265
char s[N];
bool have_value[N];
int left[N],right[N],v[N];
#define root 1
bool failed;
int cnt;
inline int newnode(){
	return ++cnt;
}
void addnode(int value,char*s){
	int u=root;
	int len=strlen(s)-1;
	forplus(i,0,len){
		//	注意,里面是u不是i 
		if(s[i]=='L'){
			if(left[u]==0){
				left[u]=newnode();
			}
			u=left[u];
		}else if(s[i]=='R'){
			if(right[u]==0){
				right[u]=newnode();
			}
			u=right[u];
		}
	}
	if(have_value[u]==true)failed=true;
	have_value[u]=true;
	v[u]=value;
}
bool read_input(){
	mem(left,0),mem(right,0),mem(have_value,0);
	failed=false;
	cnt=root;//默认root位置1 
	for(;;){
		if(scanf("%s",s)!=1)return false;//读入结束 
		if(strcmp(s,"()")==0)break;//这轮读完
		int v;
		sscanf(&s[1],"%d",&v);
		if(failed==false)addnode(v,strchr(s,',')+1);
	}
	return true;
}
bool bfs(vector<int>&ans){
	queue<int>q;
	q.push(root);
	while(!q.empty()){
		int now=q.front();q.pop();
		if(have_value[now]==false)return false;
		ans.push_back(v[now]);
		if(left[now])q.push(left[now]);
		if(right[now])q.push(right[now]);
	}
	return true;
}
int main(){
	while(read_input()){
		vector<int> ans;
		if(failed==false&&bfs(ans)){
			int len=ans.size();
			forplus(i,0,len){
				if(i)putchar(' ');
				printf("%d",ans[i]);
			}
			putchar('\n');
		}else{
			printf("not complete\n");
		}
	}
}

  1. 内存池
//#pragma GCC optimize(3,"Ofast","inline")
//#pragma GCC optimize(2)
#include<stdio.h>
#include<string.h>
#include<queue>
#ifdef LOCAL
FILE*FP=freopen("text.in","r",stdin);
//FILE*fp=freopen("text.out","w",stdout);
#endif
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
#define _forplus(i,a,b) for( register int i=(a); i<=(b); i++)
#define forplus(i,a,b) for( register int i=(a); i<(b); i++)
#define _forsub(i,a,b) for( register int i=(a); i>=(b); i--)
#define _forauto(a,b) for(auto &(a):(b))
#define pb push_back
#define N 265
char s[N];
struct Node{
	bool have_value;
	Node*left,*right;
	int v;
}node[N];
queue<Node*>freenodes;
void init(){
	forplus(i,0,N){
		freenodes.push(node+i);
	}
}
bool failed;
int cnt;
Node* newnode(){
	Node*u=freenodes.front();freenodes.pop();
	u->left=u->right=NULL,u->have_value=false;
	return u;
}
Node * root;
void addnode(int value,char*s){
	Node*u=root;
	int len=strlen(s)-1;
	forplus(i,0,len){
		//	注意,里面是u不是i 
		if(s[i]=='L'){
			if(u->left==0){
				u->left=newnode();
			}
			u=u->left;
		}else if(s[i]=='R'){
			if(u->right==0){
				u->right=newnode();
			}
			u=u->right;
		}
	}
	if(u->have_value==true)failed=true;
	u->have_value=true;
	u->v=value;
}
void deletenode(Node*u){
	if(u==NULL)return ;
	deletenode(u->left);
	deletenode(u->right);
	freenodes.push(u);
}
bool read_input(){
	failed=false;
	deletenode(root);
	root=newnode();
	for(;;){
		if(scanf("%s",s)!=1)return false;//读入结束 
		if(strcmp(s,"()")==0)break;//这轮读完
		int v;
		sscanf(&s[1],"%d",&v);
		if(failed==false)addnode(v,strchr(s,',')+1);
	}
	return true;
}
bool bfs(vector<int>&ans){
	queue<Node*>q;
	q.push(root);
	while(!q.empty()){
		Node* now=q.front();q.pop();
		if(now->have_value==false)return false;
		ans.push_back(now->v);
		if(now->left)q.push(now->left);
		if(now->right)q.push(now->right);
	}
	return true;
}
int main(){
	init();
	while(read_input()){
		vector<int> ans;
		if(failed==false&&bfs(ans)){
			int len=ans.size();
			forplus(i,0,len){
				if(i)putchar(' ');
				printf("%d",ans[i]);
			}
			putchar('\n');
		}else{
			printf("not complete\n");
		}
	}
}

4.字符串

#include<bits/stdc++.h>
#ifdef LOCAL
FILE*FP=freopen("text.in","r",stdin);
//FILE*fp=freopen("text.out","w",stdout);
#endif
using namespace std;
#define N 266
string tree[N];
#define sub(k) k.substr(k.find(',')+1,k.end()-k.begin()-k.find(',')-2)//find返回第几个 
bool mycmp(string a,string b){
	//return sub(a)<sub(b);这是先根dfs...
	if(sub(a).size()==sub(b).size())return sub(a)<sub(b);
	return sub(a).size()<sub(b).size();
}
int main(){
	int cnt=0;
	while(cin>>tree[++cnt]){
		if(tree[cnt]=="()"){
			cnt--;
			sort(tree+1,tree+(cnt+1),mycmp);
			map<string,int>m;
			bool failed=false;
			for(int i=1;i<=cnt;i++){
				//cout<<tree[i]<<'\n';
				if(++m[sub(tree[i])]>=2){
					failed=true;break;
				}
			}
			for(int i=1;i<=cnt;i++){
				if(m[sub(tree[i]).substr(0,sub(tree[i]).size()-1)]==0){
					failed=true;break;
				}
			}
			if(failed){
				printf("not complete\n");
			}else{
				for(int i=1;i<=cnt;i++){
					if(i!=1)putchar(' ');
					cout<<tree[i].substr(1,tree[i].find(',')-1);
				}
				putchar('\n');
			}
			cnt=0;
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值