2016-05-23 15 views
2

我需要为Node和Binary Tree编写一个类,两者都工作得很好。我还需要为方法使用菜单,当我尝试添加某些内容时,它会添加,但会立即重置为None,并在调用add时重新开始。这是菜单实现。在Python中执行二叉树的错误

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") 
+0

你是什么意思'重置为无,重新开始'? – polku

+2

无论您提供什么输入,您显示的代码都只会运行一次,因为没有循环。假设你放置循环,确保将'tree = BinaryTree()'移出菜单,因为你不想每次都重新初始化它。否则它会失去它的状态。 – algrebe

回答

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")