2


我玩了一下二叉树并构建了一个菜单,当我单击创建树时,用户可以选择是构建二叉树、向他构建的二叉树插入值还是删除它。树被创建,然后菜单再次出现,现在我想在这棵树中放一个数字,但是在案例中没有设置该变量,每个案例都应该设置它的变量?或者你可以使用全局变量?
这是我的菜单类代码。

import java.util.Comparator;
 import java.util.Scanner;


 public class TreeMenu {

 public static void main(String[] args) {

     while(true ){
         System.out.println("\n------------Menu-----------");
         System.out.println("1. Create Tree");
         System.out.println("2. Delete Tree");
         System.out.println("3. Insert Value INTO the tree");
         System.out.println("4. Exit ");
         System.out.println("Please Select Your Choice");

         Scanner choice = new Scanner(System.in); 
         int i = choice.nextInt();
         if(i>0 && i<=4){
         switch (i)
          {

            case 1:{

                System.out.println("Creating a Tree Please Wait........");
                Comparator comp = new IntegerComparator();
                BST tree1 = new BST(comp);
                break;
            }
            case 2:{
                System.out.println("You Chose TWO");
                break;
            }
            case 3:{
                Scanner Number = new Scanner(System.in); 
                 int num = Number.nextInt();
                 tree1.insert(num);

            }
            case 4:{
                System.exit(0);

            }

           }

          }
         else{
             System.out.println("There is no number in the menu like that "+i);
             System.exit(0); 

         }
     }

 }

 }

我如何使用创建并插入他的值的同一棵树?
谢谢

4

1 回答 1

3

声明tree1为私有全局变量

  public class TreeMenu {
    private static BST tree1 = null;
    .....

现在tree1在里面实例化它switch case 1,然后你可以在里面使用相同的树变量case 2

A thing to note is you would need to do error checking in case 2 and 3, if tree1 == null, that would mean no tree has been created yet.

于 2013-02-09T15:32:38.740 回答