【问题标题】:Error in Binary Tree Implementation in PythonPython中二叉树实现的错误
【发布时间】:2018-02-02 18:49:58
【问题描述】:

我需要为节点和二叉树编写一个类,它们都可以正常工作。我还需要为方法使用菜单,当我尝试添加某些内容时,它会添加但立即重置为 None 并在调用 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")

【问题讨论】:

  • 你是什么意思'它重置为无并重新开始'?
  • 您显示的代码将只运行一次,而与您提供的输入无关,因为没有循环。假设您放置了循环,请确保将 tree = BinaryTree() 移到菜单之外,因为您不想每次都重新初始化它。否则它将失去它的状态。

标签: python binary-tree binary-search-tree binary-search


【解决方案1】:

正如上面的评论所暗示的,您需要一个 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")

【讨论】:

    猜你喜欢
    • 2019-04-15
    • 1970-01-01
    • 2012-01-09
    • 2021-02-20
    • 2021-04-16
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多