首页 > 其他分享 >1020 Tree Traversals

1020 Tree Traversals

时间:2023-04-20 18:24:42浏览次数:47  
标签:遍历 1020 int inorder Traversals Tree line include root

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

代码实现:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <unordered_map>
#include <queue>

using namespace std;

const int N = 40;

int n,count1;
int postorder[N], inorder[N];               //后序遍历,中序遍历
unordered_map<int, int> l, r, pos;          //用哈希表模拟二叉树

int build(int il, int ir, int pl, int pr)
{
	if(il>ir||pl>pr) return -1; 
    int root = postorder[pr];
    int k = pos[root];                      //得到根节点在中序遍历中的下标

    //k大于il表示根节点左边还有节点,即当前根节点存在左子树,下同
    //下面两行是难点,举例解释见图
	if(il<k)l[root] = build(il, k - 1, pl, pl + k - 1 - il);
	if(ir>k)r[root] = build(k + 1, ir, pl + k - il, pr - 1);

    return root;
}

void bfs(int root)                          //BFS用来层序遍历输出
{
    queue<int> q;
    q.push(root);
    while (q.size())
    {
        auto t = q.front();
        q.pop();
        if(t==-1)continue;
        if(count1==0)cout<<t;
        else cout <<" "<<t;
        count1++;
        if (l[t]) q.push(l[t]);       //判断该节点的左右儿子是否存在
        if (r[t]) q.push(r[t]);       //存在则加入队列,等待下一层遍历
    }
}

int main()
{
    cin >> n;
    for (int i = 0; i < n; i ++ ) cin >> postorder[i];
    for (int i = 0; i < n; i ++ )
    {
        cin >> inorder[i];
        pos[inorder[i]] = i;                //记录中序遍历每个点位置(剪枝)
    }

    int root = build(0, n - 1, 0, n - 1);   //参数为中序遍历区间和后序遍历区间
    bfs(root);

    return 0;
}

 

标签:遍历,1020,int,inorder,Traversals,Tree,line,include,root
From: https://www.cnblogs.com/hxss/p/17337815.html

相关文章

  • ztree初始化时选中(ruoyi版)
    ruoyi版本:4.6.0问题描述将后台传入的参数放到$.tree中,当ztree的Node中checked为true时,Node默认为选中,目前前台调用代码varurl=ctx+"获得List<Ztree>的URL";varoptions={url:url,expandLevel:2,beforeClick:function(treeId,treeNode,clickFlag){......
  • java 用 Java 将 HashMap 转换为 TreeMap 的程序
    转载自:https://www.moonapi.com/news/24923.html HashMap 是Java1.2以来Java集合的一部分。它提供了以(键、值)对存储数据的JavaMap接口的基本实现。要访问HashMap中的值,必须知道它的键。哈希映射被称为哈希映射,因为它使用哈希技术来存储数据。Java中的树图和抽象......
  • biTree
    #include<stdio.h>#include<stdlib.h>typedefcharTElemType;typedefstructBiTNode{TElemTypedata;structBiTNode*lchild,*rchild;}BiTNode,*BiTree;typedefBiTreeSElemType;#defineSTACK_INIT_SIZE100#defineSTACKINCR......
  • gitee github 左侧栏树形显示插件 Octotree codetree 浏览器插件
    起因看到一位仁兄用gitee做仓库https://gitee.com/zhengqingya/java-developer-document然后左侧栏挺方便(抖音视频)下载chrome扩展市场搜octotree用于githubcodetree用于gitee双核浏览器扩展市场搜octotree用于githubgitcodetree用于gitee......
  • pyqt5-QTreeWidget
    1、介绍树形组件2、类和初始化classQTreeWidget(QTreeView):"""QTreeWidget(parent:QWidget=None)"""def__init__(self,parent=None):pass3、属性4、方法(1)setColumnCount设置列数,参数为int类型。树形组件只能是设置为1(2)setHeaderLabels设......
  • C++20 Advent of Code 可见树 Day 8: Treetop Tree House
    C++20AdventofCode可见树Day8:TreetopTreeHouseDay8-AdventofCode2022#include<iostream>#include<vector>#include<fstream>#include<string>#include<ranges>#include<numeric>#include<algorithm>#in......
  • [oeasy]python0135_python_语义分析_ast_抽象语法树_abstract_syntax_tree
    语义分析_抽象语法树_反汇编回忆上次回顾了一下历史python是如何从无到有的看到Guido长期的坚持和努力python究竟是如何理解print("hello")的?这些ascii字母如何被组织起来执行?纯文本首先编写Guido的简历print("1982------Guidoincwi")print("1995------Guidoincnri")pri......
  • 索引结构-B-tree
         ......
  • [oeasy]python0135_python_语义分析_ast_抽象语法树_abstract_syntax_tree
    语义分析_抽象语法树_反汇编回忆上次回顾了一下历史python是如何从无到有的看到Guido长期的坚持和努力 ​ 添加图片注释,不超过140字(可选) python究竟是如何理解print("hello")的?这些ascii字母如何被组织起来执行? ......
  • Qt5.9 UI设计(五)——将Tabwidget与treeWidget相互关联
    前言前面一章介绍了ControlTabWidgetControlTreeWidgetmaintitlebar三个子页面同时布局到mainwindow的方法,本章介绍如何将ControlTreeWidget与ControlTabWidget联动。(一)TabWidget子页面实现在maincontent目录下创建otaparatarnsmittelnettester五个目录,用来......