当前位置:网站首页>信息学奥赛一本通 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;
}
边栏推荐
- leetcode刷题:二叉树12(二叉树的所有路径)
- Oracle-表空间管理
- 通配符选择器
- [C language] string function and Simulation Implementation strlen & strcpy & strcat & StrCmp
- [quick start of Digital IC Verification] 3. Introduction to the whole process of Digital IC Design
- [C language] merge sort
- 【数字IC验证快速入门】1、浅谈数字IC验证,了解专栏内容,明确学习目标
- leetcode刷题:二叉树17(从中序与后序遍历序列构造二叉树)
- id选择器和类选择器的区别
- BZOJ 3747 POI2015 Kinoman 段树
猜你喜欢
Complete interview questions for interviewers and senior Android engineers in front-line Internet enterprises

leetcode刷题:二叉树14(左叶子之和)

Unity编辑器扩展 UI控件篇

Elk distributed log analysis system deployment (Huawei cloud)

js实现禁止网页缩放(Ctrl+鼠标、+、-缩放有效亲测)

Leetcode brush questions: binary tree 18 (largest binary tree)

Leetcode skimming: binary tree 16 (path sum)

third-party dynamic library (libcudnn.so) that Paddle depends on is not configured correctl

Debezium series: record the messages parsed by debezium and the solutions after the MariaDB database deletes multiple temporary tables

Securerandom things | true and false random numbers
随机推荐
ACM getting started Day1
Thread pool parameters and reasonable settings
Leetcode brush questions: binary tree 11 (balanced binary tree)
处理文件和目录名
.Net分布式事务及落地解决方案
股票开户哪里好?网上客户经理开户安全吗
Leetcode brush question: binary tree 13 (the same tree)
ICTCLAS word Lucene 4.9 binding
计算lnx的一种方式
How to retrieve the root password of MySQL if you forget it
leetcode刷题:二叉树11(平衡二叉树)
Common operators and operator priority
95后阿里P7晒出工资单:狠补了这个,真香...
浅浅的谈一下ThreadLocalInsecureRandom
Wildcard selector
id选择器和类选择器的区别
[quick start of Digital IC Verification] 3. Introduction to the whole process of Digital IC Design
c——顺序结构
leetcode刷题:二叉树10(完全二叉树的节点个数)
Go language learning tutorial (XV)