UVA 122 - Trees on the level

 

Background

 

Trees are fundamental in many branches of computer science. Current state-of-the art parallel computers such as Thinking Machines' CM-5 are based onfat trees. Quad- and octal-trees are fundamental to many algorithms in computer graphics.

This problem involves building and traversing binary trees.

 

The Problem

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 alevel-ordertraversal of a tree, the data in all nodes at a given level are printed in left-to-right order and all nodes at levelkare printed before all nodes at levelk+1.

For example, a level order traversal of the tree

picture28

 

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) wherenis the value at the node whose path from the root is given by the strings. A path is given be a sequence ofL's andR's whereLindicates a left branch andRindicates 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 becompletely specifiedif every node on all root-to-node paths in the tree is given a value exactly once.

 

The 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.

 

The 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

 

 

Solution1:

 

#define RUN
#ifdef RUN

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
const int MAXN = 256;

typedef struct TNode{
  int have_value;	//是否被赋值过
  int v;			//节点值
  struct TNode* left, *right;	//左子树和右子树
} Node;

Node* root;

//创建节点
Node* newnode() {
  Node* u = (Node*) malloc(sizeof(Node));
  //初始化
  if(u != NULL) {
    u->have_value = 0;
    u->left = u->right = NULL;
  }
  return u;
}

int failed;
//添加一个节点
void addnode(int v, char* s) {
  int n = strlen(s);
  Node* u = root;		//从根节点开始向下走
  for(int i = 0; i < n; i++)
    if(s[i] == 'L') {
	  //节点不存在则建立新节点
      if(u->left == NULL) u->left = newnode();
	  //向左走
      u = u->left;
    } 
	else if(s[i] == 'R') {
      if(u->right == NULL) u->right = newnode();
      u = u->right;
    }//忽略其他情况,即最后那个多余的右括号


	//已经赋过值,表示输入有误
	if(u->have_value) failed = 1;
	u->v = v;
	u->have_value = 1;	//标记赋过值
}

//删除树
void remove_tree(Node* u) {
  if(u == NULL) return;
  remove_tree(u->left);
  remove_tree(u->right);
  free(u);
}

//保存读入节点
char s[MAXN + 10];

//输入部分
int read_input() {
  failed = 0;
  
  //防止内存泄露
  remove_tree(root);

  //创建根节点
  root = newnode();
  for(;;) {
    if(scanf("%s", s) != 1) return 0;
	// 读到结束标志(),退出循环
    if(!strcmp(s, "()")) break;

    int v;
	//读入节点值
    sscanf(&s[1], "%d", &v);
	//查找逗号的位置,并插入节点
    addnode(v, strchr(s, ',')+1);
  }
  return 1;
}

//节点总数和输出序列
int n = 0, ans[MAXN];
//BFS输出
int bfs() {
  int front = 0, rear = 1;
  Node* q[MAXN];
  //初始时只有一个根节点
  q[0] = root;
  while(front < rear) {
    Node* u = q[front++];
	//有节点没有被赋值过,表示输入有误
    if(!u->have_value) return 0;
	//增加到输出序列的尾部
    ans[n++] = u->v;
	//如果有左儿子,就放进队列
    if(u->left != NULL) q[rear++] = u->left;
	//如果有右儿子,就放进队列
    if(u->right != NULL) q[rear++] = u->right;
  }
  return 1;
}

int main() {

#ifndef ONLINE_JUDGE
	freopen("122.in", "r", stdin);
	freopen("122.out", "w", stdout); 
#endif

  while(read_input()) {
	
    if(!bfs()) failed = 1;
    if(failed) printf("not complete\n");
    else {
      for(int i = 0; i < n; i++){
		  if(i==n-1){
			  printf("%d", ans[i]);
		  }
		  else{
			  printf("%d ", ans[i]);
		  }
	  }
        
      printf("\n");
    }
	n = 0;
  }
  return 0;
}

#endif



 

 

Solution2:

 

#define RUN
#ifdef RUN

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
const int MAXN = 256;
const int root = 1;
int cnt, vis[MAXN], val[MAXN], left[MAXN], right[MAXN];

int newnode() { int u = ++cnt; left[u] = right[u] = 0; return u; }
void newtree() { left[root] = right[root] = 0; cnt = root; }

int failed;
void addnode(int v, char* s) {
  int n = strlen(s), u = root;
  for(int i = 0; i < n; i++)
    if(s[i] == 'L') {
      if(!left[u]) left[u] = newnode(); u = left[u];
    } else if(s[i] == 'R') {
      if(!right[u]) right[u] = newnode(); u = right[u];
    }
  if(vis[u]) failed = 1;
  val[u] = v;
  vis[u] = 1;
}

char s[MAXN + 10];
int read_input() {
  failed = 0;
  newtree();
  for(;;) {
    if(scanf("%s", s) != 1) return 0;
    if(!strcmp(s, "()")) break;
    int v;
    sscanf(&s[1], "%d", &v);
    addnode(v, strchr(s, ',')+1);
  }
  return 1;
}

int n = 0, ans[MAXN];
int bfs() {
  int front = 0, rear = 1;
  int q[MAXN];
  q[0] = root;
  while(front < rear) {
    int u = q[front++];
    if(!vis[u]) return 0;
    ans[n++] = val[u];
    if(left[u]) q[rear++] = left[u];
    if(right[u]) q[rear++] = right[u];
  }
  return 1;
}

int main() {

#ifndef ONLINE_JUDGE
	freopen("122.in", "r", stdin);
	freopen("122.out", "w", stdout); 
#endif


  while(read_input()) {
	
    if(!bfs()) failed = 1;
    if(failed) printf("not complete\n");
    else {
      for(int i = 0; i < n; i++){
		  if(i == n-1){
			  printf("%d", ans[i]);
		  }
		  else{
			  printf("%d ", ans[i]);
		  }
	  }
      printf("\n");
    }

	n = 0;
	cnt = 0;
	memset(ans, 0, sizeof(ans));
	memset(vis, 0, sizeof(vis));
	memset(val, 0, sizeof(val));
	memset(left, 0, sizeof(left));
	memset(right, 0, sizeof(right));
  }
  return 0;
}

#endif



 

 

 

UVA122 树的层次遍历 Trees on the level(两种方法详解) UVA122 树的层次遍历 Trees on the level 输入: (11,LL) (7,LLL) (8,R) (5,) (4,L) (13,RL) (2,LLR) (1,RRR) (4,RR) () (3,L) (4,R) () 输出: 5 4 8 11 13 4 7 2 1 not complete //不管是左子树还是右子树,它们的父节点都是P/2; 以下内容来自《算法竞赛入门经... 阅读详情

相关推荐

工作:三菱PLC与伺服之CC-Link IE Field Network通讯应用

CC-LINK-IE

好记性不如烂笔头 2万+

Trees on the level (二叉搜索树的还原)

Trees are fundamental in many branches of computer science. Current state-of-the art parallel computers such as Thinking Machines' CM-5 are based on fat trees. Quad- and octal-trees are fundamental to...

自渡的博客 714

Cesium中实现阴影率分析

看到群里有人在研究这个,所以看了一下。主要是模仿超图的,实现原理超图有做回答:但其实超图的这个实现方式还是过于复杂,原因是:既然是获取太阳的日照阴影,而Cesium中原本就存在太阳,且能投射阴影,因此其实并不需要再次计算太阳位置并计算视锥获取深度图,直接使用Cesium原生的太阳深度图即可。

weixin_43481439的博客 2216

UVA-122-TREE ON THE LEVEL

UVA-122-TREE ON THE LEVELsubjectTrees are fundamental in many branches of computer science. Current state-of-the art parallel computers such as Thinking Machines’ CM-5 are based on fat trees. Quad- and

丹朗的博客 416

国产机载操作系统天脉ACoreOS实战:从零搭建开发环境到应用移植

本文详细介绍了国产机载操作系统天脉ACoreOS的实战开发流程,从核心特性解析到开发环境搭建,再到VxWorks应用移植策略。重点阐述了其符合ARINC 653标准的时空分区架构如何保障高可靠性,并提供了从零创建分区工程、重构通信与任务代码的具体步骤,为开发者向这一国产化平台迁移提供了实用指南。

flower的专栏 633

1. 基于STM32的1.28寸圆形IPS屏(GC9A01)驱动移植实战:软件SPI与硬件SPI双方案详解

本文详细介绍了如何在STM32平台上为1.28寸圆形IPS屏(GC9A01驱动芯片)移植驱动程序,涵盖软件SPI与硬件SPI两种实现方案。内容从引脚定义、工程搭建、GPIO配置到SPI外设初始化逐步详解,并提供了完整的测试代码,帮助开发者根据项目需求(灵活性或性能)选择合适的通信方式,快速点亮屏幕并集成到智能手表等嵌入式项目中。

weixin_42300144的博客 203

A - Trees on the level(树的层序遍历)

主要使用了c++STL中的set。用排序的方法对输入进行排序,根据字符的长度以及相同长度的字典序从小到大,正好对应树从上到下。1.某些节点无法从根节点出发到达。2.开始处理数据时都需要清空路径。...

zjsru_Beginner的博客 364

爆肝5万字❤️Open3D 点云数据处理基础(Python版)

本文为Open3D 点云数据处理基础教程(Python版),小白也能轻松上手!还等什么呢,学起来!

孙悟空 13万+

Trees on the level

Trees are fundamental in many branches of computer science. Current state-of-the art parallel computers such as Thinking Machines' CM-5 are based on fat trees. Quad- and octal-trees are fundamental to...

huifeng_的博客 534

Cursor使用教程:用 Cursor 创建第一个 Java 项目

Cursor是一款基于VS Code的AI编程编辑器,专为开发者设计。安装前需确保JDK 8+、Maven 3.8+等环境配置,支持Windows系统。编辑器提供中文界面选项,可通过扩展市场安装语言包。创建Java项目支持手动和AI提示词两种方式:手动需创建目录结构并编写代码;AI方式则通过自然语言描述快速生成项目框架和代码。标准Java项目包含src/main/java主代码目录、src/test/java测试目录及pom.xml等配置文件。Maven项目中,pom.xml是核心配置文件,管理项目依赖与构

博客 3547

64.企业级案例(上)-金融行业DDD落地全流程支付系统-附架构演进图

本文以金融支付系统为例,完整展示了DDD在企业级项目中的落地流程。首先通过事件风暴识别核心业务领域,包括交易、渠道、账务等限界上下文。在战略设计中划分上下文边界,确定交易上下文为核心域。战术设计聚焦交易上下文,详细设计了支付单聚合、值对象和支付路由服务。架构实现采用CQRS+EDA模式,通过命令端处理交易,查询端异步更新读模型,并利用防腐层隔离外部渠道。案例展示了DDD从业务探索到架构实现的全过程,体现了其在复杂业务系统中的价值。

yonggeit的博客 3037

Uva - 122 - Trees on the level

难点在于二叉树的生成和宽度优先遍历BFS,最后要注意防止内存泄漏,虽然题目没有内存限制,但是优化考虑还是做一下释放内存,因为这个不是效率型的问题,测试时间短到没有无法显示。 AC代码: #include <iostream> #include <cstdio> #include <cstdlib> #include <...

anpi3191的博客 178

机器人在果园内行巡检仿真(2D雷达、realsense相机)

DiffBot是一种具有两个轮子的自主差动驱动机器人。它的主要处理单元是一个运行Ubuntu Mate 20.04和ROS 1 (ROS Noetic)中间件的Raspberry pi4b。该存储库包含ROS驱动包、真实机器人的ROS控制硬件接口和模拟DiffBot的配置。修改配置文件orchard_world.launch。

如果想成为中心,那么就到中心去吧。 1311

uva122 trees on the level

看不下去,找点简单的,再回来写

Dosth_Magic 625

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

(二叉树建树 先序遍历)UVA_122 Trees on the level

UVA_122 Trees on the level题意让我们构建一棵树,给出每一个节点是从根节点怎么走才能走到. 比如(11,LL)就是根节点的左子树的左子节点的位置权值为11.然后让给出这棵树的先序遍历结果. 如果出现下列情况,输出”not complete” 重复赋值 没有根节点 有节点没有被赋值 给出超过一个节点 解决这个题的输入比较坑啊,刚上来感觉解决不了…

ZhangYang 410

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

Trees on the level UVA - 122

Trees on the level UVA - 122 紫书6.3.2 二叉树的层次遍历 采用动态结构创建二叉树 #include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <queue> using namespace s...

NaNa 154

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

UVA.122 Trees on the level(二叉树 BFS)

UVA.122 Trees on the level(二叉树 BFS)题意分析给出节点的关系,按照层序遍历一次输出节点的值,若树不完整,则输出not complete代码总览#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> #include <vector> #

Pengwill's Blog 361

UVA-122(Trees on the level)

Trees on the level 题目链接: https://vjudge.net/problem/UVA-122 题目意思: 给你一些(,)让你建立一棵树,直到输入()结束建树,然后判断树是否完整,如果没有结点未赋值或者被赋值两次,就按层次遍历输出树,否则输出not complete 代码: #include <algorithm> #include <m...

weixin_30278237的博客 91

UVa Problem 122 - Trees on the level

// UVa Problem 122 - Trees on the level // Verdict: Accepted // Submission Date: 2011-12-25 // UVa Run Time: 0.008s // // 版权所有(C)2011,邱秋。metaphysis # yeah dot net // // [解题方法] // 本题可以归结为数据结构问题。步骤是建立树结

寂静山林 4540

UVa122 (树的层次遍历 Trees on the level)

1、题目大意 题目链接UVa 122 给出二叉树的各个结点,建立二叉树,然后按层次遍历输出各个节点的值。 每个结点的描述为 (n, s) 。n 表示结点值,为正整数。s 为一个 L 和 R 组成的字符串,表示从树根到该结点的路径,L 表示左子树,R 表示右子树。每棵树的结点输入以 () 作为结束,整个输入以 EOF 作为结束。 如果生成的二叉树不完整,或者树中的某个结点重复了,则输出 no...

Armstrong的博客 899

UVa122-Trees on the level

UVa122-Trees on the level 1.题目描述:点击链接 2.问题分析: 简单地来说,就是输入一组字符串,表示二叉树上某些节点的值和位置,这些节点不一定可以组成一颗完整的二叉树,可能出现缺少某个节点或者某个节点冗余的情况。 需要我们进行判断是否能组成一颗完整的二叉树,若可以按照由上到下,由左到右的顺序输出每个节点的值,若不能...

我来人间打个滚 190

Trees on the level UVa122

一开始写的指针实现的版本,貌似存在内存泄漏问题,输入之间有蜜汁相互作用,后改为数组实现,AC。指针版本:#include &lt;cstdio&gt; #include &lt;queue&gt; #include &lt;vector&gt; using namespace std; char x[300], cmd[300]; int flag; struct node{ int ...

比宇宙更远的地方- 277

[UVA122]Trees on the level

以任意顺序给出一棵二叉树的节点,格式如: (5,LLRL), 数字表示该节点的值. 要求输出一棵树中从一个叶子走到根节点的取到最小权值和的那个叶子节点,假如有多个叶子节点能取到最小的权值,则输出叶子权值本身最小的那个叶子.题目保证了每个节点的权值都是不同的.假如一组输入,存在一个节点被赋值超过1次或者没被赋值,则输出"not complete".每组输入用()作为该组数据的终结符 题目其实没啥

Long days journey into the night 480

UVa 122 Trees on the Level

本文介绍了如何根据给定的节点描述序列构建二叉树并输出其层序遍历结果。每个节点由一个正整数和路径字符串表示,路径字符串指示节点在树中的位置。若树完全指定(每个节点仅赋值一次),则输出层序遍历结果;否则输出"not complete"。解题步骤包括动态建树、检查节点赋值完整性、层序遍历输出和内存管理。算法时间复杂度为O(N),空间复杂度为O(N)。代码实现采用递归遍历和动态内存管理,适用于二叉树基本操作练习。

寂静山林 351
上一篇: UVA 679 - Dropping Balls
下一篇: UVA 122 - Trees on the level
chiiis
博客等级 码龄14年 422粉丝 429原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值