Skip to content

27948: FBI树

http://cs101.openjudge.cn/practice/27948/

我们可以把由 0 和 1 组成的字符串分为三类:全 0 串称为 B 串,全 1 串称为 I 串,既含 0 又含 1 的串则称为 F 串。 FBI 树是一种二叉树,它的结点类型也包括 F 结点,B 结点和 I 结点三种。 由一个长度为 2^N 的 01 串 S 可以构造出一棵 FBI 树 T,递归的构造方法如下:

  1. T 的根结点为 R,其类型与串 S 的类型相同;
  2. 若串 S 的长度大于 1,将串 S 从中间分开,分为等长的左右子串 S1 和 S2;由左子串 S1 构造 R 的左子树 T1,由右子串 S2 构造 R 的右子树 T2。

现在给定一个长度为 2^N 的 01 串,请用上述构造方法构造出一棵 FBI 树,并输出它的后序遍历序列。

输入

第一行是一个整数 N,0<= N <= 10。 第二行是一个长度为 2^N 的 01 串。

输出

包含一行,这一行只包含一个字符串,即 FBI 树的后序遍历序列。

样例输入

sample1 input:
3
10001011

sample1 output:
IBFBBBFIBFIIIFF

样例输出

sample2 input:
2
0000

sample2 output:
BBBBBBB

提示

tags: binary tree

来源

AcWing 419, https://www.acwing.com/problem/content/421/

python
def construct_FBI_tree(s):
    # 判断当前字符串的类型
    if '0' in s and '1' in s:
        node_type = 'F'
    elif '1' in s:
        node_type = 'I'
    else:
        node_type = 'B'
    
    if len(s) > 1:  # 如果字符串长度大于1,则继续分割
        mid = len(s) // 2
        # 递归构建左右子树,并将结果按后序遍历拼接
        left_tree = construct_FBI_tree(s[:mid])
        right_tree = construct_FBI_tree(s[mid:])
        return left_tree + right_tree + node_type
    else:  # 如果字符串长度为1,直接返回该节点类型
        return node_type

N = int(input())
s = input()
print(construct_FBI_tree(s))
python
# ==谭訸 生命科学学院==
class Node:
    def __init__(self):
        self.value = None
        self.left = None
        self.right = None

def build_FBI(string):
    root = Node()
    if '0' not in string:
        root.value = 'I'
    elif '1' not in string:
        root.value = 'B'
    else:
        root.value = 'F'
    l = len(string) // 2
    if l > 0:
        root.left = build_FBI(string[:l])
        root.right = build_FBI(string[l:])
    return root

def post_traverse(node):
    ans = []
    if node:
        ans.extend(post_traverse(node.left))
        ans.extend(post_traverse(node.right))
        ans.append(node.value)
    return ''.join(ans)

n = int(input())
string = input()
root = build_FBI(string)
print(post_traverse(root))