当前位置:网站首页>信息学奥赛一本通 1340:【例3-5】扩展二叉树
信息学奥赛一本通 1340:【例3-5】扩展二叉树
2022-07-05 20:10:00 【君义_noip】
【题目链接】
【题目考点】
1. 二叉树
【解题思路】
解法1:
用getchar()或cin.get()每次读取一个字符。
先序序列的格式为:<根结点> <左子树的先序序列> <右子树的先序序列>
可以用递归的方法构建二叉树:
- 读入一个字符,作为根结点
- 递归构建左子树
- 递归构建右子树
- 将左右子树接在这棵树根结点的下面,返回根结点的地址
完成树的构建后,再输出这棵树的中序和后序遍历序列。
【题解代码】
解法1:
#include <bits/stdc++.h>
using namespace std;
struct Node//二叉树结点
{
char val;
int left, right;
};
Node node[1000];//结点池
int p = 1;
void inOrder(int r)//中序遍历
{
if(r != 0)
{
inOrder(node[r].left);
cout << node[r].val;
inOrder(node[r].right);
}
}
void postOrder(int r)//后序遍历
{
if(r != 0)
{
postOrder(node[r].left);
postOrder(node[r].right);
cout << node[r].val;
}
}
int createTree(char val)//传入要生成的二叉树的根的值,返回生成的二叉树的地址
{
int np;
if(val == '.')
return 0;
else
{
np = p++;
node[np].val = val;
node[np].left = createTree(cin.get());//读入字符,构建左子树
node[np].right = createTree(cin.get());//读入字符,构建右子树
return np;
}
}
int main()
{
int root = createTree(cin.get());
inOrder(root);
cout << endl;
postOrder(root);
return 0;
}
边栏推荐
- Cocos2d-x项目总结中的一些遇到的问题
- C langue OJ obtenir PE, ACM démarrer OJ
- Build your own website (16)
- 【数字IC验证快速入门】2、通过一个SoC项目实例,了解SoC的架构,初探数字系统设计流程
- 【数字IC验证快速入门】7、验证岗位中必备的数字电路基础知识(含常见面试题)
- ICTCLAS用的字Lucene4.9捆绑
- The difference between ID selector and class selector
- Codeforces Round #804 (Div. 2) - A, B, C
- 无卷积骨干网络:金字塔Transformer,提升目标检测/分割等任务精度(附源代码)...
- Is it safe for Anxin securities to open an account online?
猜你喜欢
leetcode刷题:二叉树17(从中序与后序遍历序列构造二叉树)
【数字IC验证快速入门】7、验证岗位中必备的数字电路基础知识(含常见面试题)
.Net分布式事务及落地解决方案
秋招字节面试官问你还有什么问题?其实你已经踩雷了
Based on vs2017 and cmake GUI configuration, zxing and opencv are used in win10 x64 environment, and simple detection of data matrix code is realized
14. Users, groups, and permissions (14)
JS implementation prohibits web page zooming (ctrl+ mouse, +, - zooming effective pro test)
kubernetes资源对象介绍及常用命令(五)-(ConfigMap&Secret)
Oracle-表空间管理
leetcode刷题:二叉树13(相同的树)
随机推荐
如何安全快速地从 Centos迁移到openEuler
【数字IC验证快速入门】3、数字IC设计全流程介绍
Go language | 02 for loop and the use of common functions
什么是pyc文件
JS implementation prohibits web page zooming (ctrl+ mouse, +, - zooming effective pro test)
kubernetes资源对象介绍及常用命令(五)-(ConfigMap&Secret)
leetcode刷题:二叉树12(二叉树的所有路径)
Common operators and operator priority
After 95, Alibaba P7 published the payroll: it's really fragrant to make up this
third-party dynamic library (libcudnn.so) that Paddle depends on is not configured correctl
Notes on key vocabulary in the English original of the biography of jobs (12) [chapter ten & eleven]
Fundamentals of deep learning convolutional neural network (CNN)
Four methods of random number generation | random | math | threadlocalrandom | securityrandom
How to safely and quickly migrate from CentOS to openeuler
leetcode刷题:二叉树10(完全二叉树的节点个数)
How to retrieve the root password of MySQL if you forget it
.Net分布式事务及落地解决方案
. Net distributed transaction and landing solution
Thread pool parameters and reasonable settings
leetcode刷题:二叉树11(平衡二叉树)