为什么我的二叉树在给定不同的字节字符串时表现不同?

Why does my binary tree behave differently given different byte strings?

我一直在用 python 练习递归,目前正试图停止一直递归到单个字节,而是在某个字节大小处停止。在此示例中,我选择 2,因此在我的代码中,如果要生成的潜在 children 中的任何一个小于 2,它将不会递归,只会 return 当前节点。它对第一个字节字符串工作正常,但对接下来的两个字节字符串失败。为什么会发生这种情况,我该如何解决?

第一个 b 的正确输出:停止 recursing/creating children 大小为 3,因为下一代 children 至少有 1 child 小于 尺寸 2

b'\x00\x01\x00\x02\x00\x03'
b'\x00\x01\x00'
b'\x02\x00\x03'

第二个 b 的输出不正确:似乎递归到单个字节

b'L_]ju\x87\xd4\x14j\x1b> \xc52'
b'L_]ju\x87\xd4'
b'L_]'
b'ju\x87\xd4'
b'ju'
b'\x87\xd4'
b'\x14j\x1b> \xc52'
b'\x14j\x1b'
b'> \xc52'
b'> '
b'\xc52'
from random import randbytes


class Node:
    def __init__(self, value):
        self.value = value
        self.children = []
        self.parent = None
        self.bytesize = len(value)
  
    def make_children(self, child):
        child.parent = self
        self.children.append(child)

    def print_tree(self):
        print(self.value)
        if len(self.children) > 0: # leaf node case
            for child in self.children:
                child.print_tree()

def build_tree(value_list):
    root = Node(value_list)
    #if len(value_list) == 1:
    if len(value_list) / 2 < 2: # MODIFY TO STOP RECURSING IF SIZE OF CHILDREN WILL BE BELOW 2
        return root
        
    mid_point = len(value_list) // 2
    left_half = value_list[:mid_point]
    right_half = value_list[mid_point:]

    child1 = build_tree(left_half)
    root.make_children(child1)

    child2 = build_tree(right_half)
    root.make_children(child2)

    return root


if __name__ == '__main__':
    #list1 = [12, 7, 8, 15, 9]
    b = b'\x00\x01\x00\x02\x00\x03'
    #b = b'\x4c\x5f\x5d\x6a\x75\x87\xd4\x14\x6a\x1b\x3e\x20\xc5\x32'
    #b = randbytes(6)
    file = build_tree(b)
    file.print_tree()
    print(len(b))

您的代码实际上按预期工作。你说的两个字节串都是2个字节,不是1个。

这是一种显示字节串的方法,可能会使其更清晰:

def print_string(s):
    print(' '.join(map('{:#2x}'.format, s)))

print_string(b'> ')
# 0x3e 0x20

print_string(b'\xc52')
# 0xc5 0x32