sicily_1935_重建二叉树解题报告

传送门:http://soj.sysu.edu.cn/1935

  • 问题已知:一棵树先序遍历序列和中序遍历序列
  • 思路:
    • 将这个树分成三部分:根,左子树,右子树。
    • 先把根插入树中,再左子树和右子树进行递归,直到所有元素都已经插入到树中即可。
// Copyright (c) Junjie_Huang@SYSU(SNO:13331087). All Rights Reserved.
// 1000_sicily_1935.cpp: http://soj.sysu.edu.cn/1935
#include 
#include 
#include 
#include 
#include 

#define MAX_SIZE 1000
#define STRING_SIZE 50

using std::cin;
using std::string;
using std::queue;

// Pre:
// @|tree[]|: the array needs to traverse
// @|pre|: the string printed by traversing a tree in pre-order
// @|mid|: the string printed by traversing a tree in mid-order
// @|index|: the index of parent node in the |tree[]|.
// Post: None
// Usage: finds the root node of a tree and sperates the |mid| with root so we
// can point out the left sub-tree and the right one. Recurses the function
// until all the elements are insert to the |tree|
void rebuild(char tree[], string pre, string mid, int index = 0) {
  // records the left child |left| and the right child |right|
  // of the parent node
  int left = 2 * index + 1, right = 2 * index + 2;
  if (pre.length()) {  // Recursions end when all the elements are inserted.
    tree[index] = pre[0];  // insert the data of the parent node

    // finds the position of root node from |mid|
    int temp = mid.find(pre[0]);

    // Recursions. Seperates the tree to its left sub-tree and the right one.
    // and the |left| and |right| will be the new parent nodes.
    rebuild(tree, pre.substr(1, temp), mid.substr(0, temp), left);
    rebuild(tree, pre.substr(temp + 1), mid.substr(temp + 1), right);
  }
}

// Pre:
// @|tree[]|: the binary tree we want to traverse with BFS. Here because
// we use an array to store the data, so we just need to traverse the array
// by the index.
// Post: Node
void BFS_visit(char tree[]) {
  for (int i = 0; i < MAX_SIZE; i++) {
    if (tree[i]) printf("%c", tree[i]);
  }
  printf("\n");
}

int main() {
  int n = 0;
  char tree[MAX_SIZE + 10];

  for (scanf("%d", &n); n; n--) {
    memset(tree, 0, sizeof(tree));
    string pre_order, mid_order;

    cin >> pre_order >> mid_order;
    rebuild(tree, pre_order, mid_order);

    BFS_visit(tree);
  }

  return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 树的概述 树是一种非常常用的数据结构,树与前面介绍的线性表,栈,队列等线性结构不同,树是一种非线性结构 1.树的定...
    Jack921阅读 4,501评论 1 31
  • 给定一个前序和中序变量的结果,写一个算法重建这棵树:前序: a b d c e f中序: d b a e c f...
    HangChen阅读 548评论 0 3
  • 这几天开学,学校还在上课,最近也是在找工作,很多天都没有更新文章,现在补一篇二叉树的文章。 最近校招公司的笔试陆续...
    zero_sr阅读 3,998评论 0 5
  • 一直以来,我都很少使用也避免使用到树和图,总觉得它们神秘而又复杂,但是树在一些运算和查找中也不可避免的要使用到,那...
    24K男阅读 6,784评论 5 14
  • 有人逼我说出他和虫子的区别。 ——— 十月,曝光默片的胶卷! 无声的把戏在人群中定格 放映员举起双手矢口否认 烈日...
    子健阅读 329评论 0 3