博客
关于我
FBI树
阅读量:326 次
发布时间:2019-03-04

本文共 1209 字,大约阅读时间需要 4 分钟。

为了解决这个问题,我们需要构造一棵FBI树,并输出其后序遍历序列。FBI树是一种二叉树,其结点分为F、B、I三种类型。构造方法基于给定的二进制串S,根结点的类型由S的类型决定,递归地处理左右子树。

方法思路

  • 构造方法:根结点的类型由字符串S的类型决定。如果S的长度大于1,将其从中间分成左右两部分,左右部分分别构造根结点的左子树和右子树,直到无法再分割。
  • 判断类型:子串如果全为0,类型为B;全为1,类型为I;否则类型为F。
  • 后序遍历:先遍历右子树,再遍历左子树,最后处理当前结点。
  • 解决代码

    #include 
    using namespace std;void work(int l, int r) { bool has_zero = false; bool has_one = false; for (int i = l; i <= r; ++i) { if (a[i] == '0') has_zero = true; if (a[i] == '1') has_one = true; } if (l == r) { if (a[l] == '0') { printf("B"); } else { printf("I"); } return; } int mid = (l + r) >> 1; // 先处理右子树 work(mid + 1, r); // 处理左子树 work(l, mid); if (has_zero && has_one) { printf("F"); } else if (has_zero) { printf("B"); } else { printf("I"); }}int main() { int n; scanf("%d", &n); int size = 1 << n; // 2^N char a[size]; for (int i = 0; i < size; ++i) { a[i] = getchar(); } work(0, size - 1); return 0;}

    代码解释

  • 读取输入:读取整数N和二进制字符串S。
  • 递归函数work:处理给定区间的子串,判断子串类型,递归处理左右子树,最后输出当前结点类型。
  • 类型判断:检查子串是否全为0、全为1或两者都有,决定结点类型。
  • 后序遍历:先处理右子树,再处理左子树,确保后序遍历顺序正确。
  • 该方法通过递归分割字符串,确保每个子串正确构造FBI树,并按后序遍历顺序输出结果。

    转载地址:http://peph.baihongyu.com/

    你可能感兴趣的文章
    NMAP网络扫描工具的安装与使用
    查看>>
    NMF(非负矩阵分解)
    查看>>
    nmon_x86_64_centos7工具如何使用
    查看>>
    NN&DL4.1 Deep L-layer neural network简介
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.7 Parameters vs Hyperparameters
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    nnU-Net 终极指南
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>