当前位置:网站首页>PAT甲级:1020 Tree Traversals
PAT甲级:1020 Tree Traversals
2022-08-02 03:27:00 【正在黑化的KS】
题目描述:
Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
7 2 3 1 5 7 6 4 1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
题目大意:给定一棵树的后序遍历和中序遍历 输出这棵树的层序遍历
解题思路:
题目的突破口是:一棵树或者一棵子树的根节点一定在后序遍历数组中的最后一个位置
所以我们可以选确定当前树的根节点是什么数字 再确定该数字在中序遍历中的下标 然后再分左右子树分别递归即可 注意中序遍历的左子树应该是inoder[:index_root],右子树应该是inorder[index_root+1:]. 而后序遍历的左右子树可以通过中序遍历的子树长度求出 因为后序遍历和中序遍历的左子树和右子树的长度应该是对应相等的
最后从根节点bfs一遍即可求出层序遍历的结果
class TreeNode(object) :
def __init__(self,x) :
self.val = x
self.left = None
self.right = None
def buildTree(posto,ino) :
if not posto : return None
root = TreeNode(posto[-1]) # #根节点为后序遍历的末位
root_index = ino.index(posto[-1]) # 确定中序遍历中,根节点的下标
# 根据根节点下标设立中序遍历的左右子树
lefti = ino[:root_index]
righti = ino[root_index+1:]
length = len(lefti) # 确定左子树长度 关键点:后序遍历和中序遍历的子树长度应该相同
# 根据中序遍历左子树长度确定后序遍历的左右子树
leftp = posto[:length]
rightp = posto[length:-1]
root.left = buildTree(leftp,lefti)
root.right = buildTree(rightp,righti)
return root # 每个节点的左右子节点应该是子树的根节点
def bfs(root) : # 输出层序遍历
if root == None : return
queue = [root]
head = 0
while queue :
print(queue[head].val)
if queue[head].left != None : queue.append(queue[head].left)
if queue[head].right != None : queue.append(queue[head].right)
queue.pop(0)
n = int(input())
posto = list(map(int,input().split())) # 后序遍历
ino = list(map(int,input().split())) # 中序遍历
root = buildTree(posto,ino)
bfs(root)
边栏推荐
猜你喜欢
随机推荐
Go Build报错汇总(持续更新)
Google Hacking
解决flex布局warp自动换行下最后一行居中问题
2021-09-04 最简单的Golang定时器应用以及最简单的协程入门儿
OPENSSL基本实验以及OPENSSL详解
mysql 原生语句点滴学习记录
关于我的数学建模~
uniapp | Problems with the use of the official map component
SATA M2 SSD 无法安装系统的解决方法
centos8 安装搭建php环境
浅谈性能优化:APP的启动流程分析与优化
Gradle源码解析:生命周期的三个阶段
Dart-Flutter DateTime日期转换
属性动画的使用和原理解析
英语每日打卡
The shooting range that web penetration must play - DVWA shooting range 1 (centos8.2+phpstudy installation environment)
关于我的大创、论文~
redis未授权访问(4-unacc)
云安全笔记:云原生全链路加密
英语每日打卡