我得到了这棵二叉树

我想把它放在一个具有以下 struct 的元组中(Left_Subtree,key,right_subtree)(其中Left_Subtree和Right_Subtree本身就是元组. 我怎样才能以正确的方式做这件事呢?

class TreeNode:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None


tree_tuple = (((None, 6, None), 4,2,(9, 7, 10)), 1,
              ((13, 11, 14),8, (15, 12, 16), 5, 3))


print(len(tree_tuple))


def parse_tuple(data):
    if isinstance(data, tuple) and len(data) == 3:
        node = TreeNode(data[1])
        node.left = parse_tuple(data[0])
        node.right = parse_tuple(data[2])
    elif data is None:
        node = None
    else:
        node = TreeNode(data)
    return node


tree = parse_tuple(tree_tuple)

print(tree.right.right.left.right.key)

我试过了,但显然我的元组 struct 甚至我的树本身有问题

推荐答案

我想这就是你想要做的.

您的parse_tuple确实也给出了12作为答案,问题出在您的tree_tuple的格式中.

我只是修改了一下我将如何处理它.

下一步是不考虑任何问题:)

class TreeNode:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None


def parse_tuple(data):
    if isinstance(data, tuple) and len(data) == 3:
        node = TreeNode(data[1])
        node.left = parse_tuple(data[0])
        node.right = parse_tuple(data[2])
        return node
    elif data is None:
        return None
    else:
        raise ValueError("Invalid Tuple Format")


tree_tuple = (
    (((None, 6, None), 4, ((None, 9, None), 7, (None, 10, None))), 2, None),
    1,
    (
        None,
        3,
        (
            (
                ((None, 13, None), 11, (None, 14, None)),
                8,
                ((None, 15, None), 12, (None, 16, None)),
            ),
            5,
            None,
        ),
    ),
)

tree = parse_tuple(tree_tuple)


print("LEFT")
print(tree.left.key)
print(tree.left.left.key)
print(tree.left.left.left.key)
print(tree.left.left.right.key)
print(tree.left.left.right.left.key)
print(tree.left.left.right.right.key)

print("\nRIGHT")
print(tree.right.key)
print(tree.right.right.key)
print(tree.right.right.left.key)
print(tree.right.right.left.left.key)
print(tree.right.right.left.left.left.key)
print(tree.right.right.left.left.right.key)
print(tree.right.right.left.right.key)
print(tree.right.right.left.right.left.key)
print(tree.right.right.left.right.right.key)

Python相关问答推荐

在IIS中运行的FastAPI-获取权限错误:[Win错误10013]试图以其访问权限禁止的方式访问插槽

计算每月过go x年的平均值

回归回溯-2D数组中的单词搜索

如何判断. text文件中的某个字符,然后读取该行

Python中的Pool.starmap异常处理

Django注释:将时差转换为小数或小数

更改Seaborn条形图中的x轴日期时间限制

如何将桌子刮成带有Se的筷子/要求/Beautiful Soup ?

如何销毁框架并使其在tkinter中看起来像以前的样子?

Python -根据另一个数据框中的列编辑和替换数据框中的列值

PywinAuto在Windows 11上引发了Memory错误,但在Windows 10上未引发

删除所有列值,但判断是否存在任何二元组

如何获取TFIDF Transformer中的值?

Streamlit应用程序中的Plotly条形图中未正确显示Y轴刻度

如何设置视频语言时上传到YouTube与Python API客户端

迭代嵌套字典的值

如何指定列数据类型

旋转多边形而不改变内部空间关系

如何在PySide/Qt QColumbnView中删除列

交替字符串位置的正则表达式