在Python中实现二叉树时出错

2024-04-16 11:10:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要为Node和Binary Tree编写一个类,这两个类都可以很好地工作。我还需要为方法使用一个菜单,当我尝试添加一些东西时,它会添加,但会立即重置为“无”,并在调用add时重新开始。这是菜单实现。你知道吗

if __name__ == '__main__':

    print("Menu \n"
        "\n"
        "1. Add item \n"
        "2. Get item \n"
        "3. Print Binary Tree in Inorder Transversal \n"
        "4. Exit \n")

    user_input = input("Please select an action from the menu: ")
    tree = BinaryTree()

    if user_input == "1":
        item = str(input("Please enter an item to add to the Binary Tree: "))
        bin_str = str(input("Please enter binary string to place in the Binary Tree: "))
        tree.add(item, bin_str)
        tree.print_inorder()

    elif user_input == "2":
        get_item = input("Please enter binary string of wanted item: ")
        get_bin_str = tree.get(get_item)
        print(get_bin_str)

    elif user_input == "3":
        tree.print_inorder())

    elif user_input == "4":
        sys.exit(0)

    else:
        print("Error: please select an action from the menu")

Tags: theanaddtreeinputgetbinitem
1条回答
网友
1楼 · 发布于 2024-04-16 11:10:37

如上所述,您需要一个while循环来允许额外的用户输入,而无需每次重置tree变量。你知道吗

if __name__ == '__main__':

    tree = BinaryTree()
    while True:

        print("Menu \n"
            "\n"
            "1. Add item \n"
            "2. Get item \n"
            "3. Print Binary Tree in Inorder Transversal \n"
            "4. Exit \n")

        user_input = input("Please select an action from the menu: ")

        if user_input == "1":
            item = str(input("Please enter an item to add to the Binary Tree: "))
            bin_str = str(input("Please enter binary string to place in the Binary Tree: "))
            tree.add(item, bin_str)
            tree.print_inorder()

        elif user_input == "2":
            get_item = input("Please enter binary string of wanted item: ")
            get_bin_str = tree.get(get_item)
            print(get_bin_str)

        elif user_input == "3":
            tree.print_inorder())

        elif user_input == "4":
            sys.exit(0)

        else:
            print("Error: please select an action from the menu")

相关问题 更多 >