我目前正在通过编写从 C++ 到 Java 的程序来学习 Java。我正在尝试使用递归二叉搜索树打印数据,但它没有打印
这是我的代码:
public class PersonRec {
int bribe;
PersonRec lchild;
PersonRec rchild;
}
import java.util.Scanner;
public class Tree {
private PersonRec root;
public Tree()
{
root = null;
}
public void Add()
{
int aBribe;
Scanner scan = new Scanner(System.in);
System.out.println("Enter person's contribution: ");
aBribe = scan.nextInt();
Insert(root, aBribe);
}
public void Insert(PersonRec root, int aBribe)
{
if(root == null)
{
root = new PersonRec();
root.rchild = null;
root.lchild = null;
root.bribe = aBribe;
}
else if(aBribe < root.bribe)
{
Insert(root.lchild, aBribe);
}
else
{
Insert(root.rchild, aBribe);
}
}
public void view()
{
if(root == null)
{
System.out.println("Tree is empty" + "\n");
}
else
DisplayTree(root);
}
public void DisplayTree(PersonRec root)
{
if(root == null)
return;
DisplayTree(root.lchild);
System.out.println(" " + root.bribe);
System.out.println("\n");
DisplayTree(root.rchild);
}
public static void main(String args[])
{
Tree myList = new Tree();
int choice;
do
{
Scanner scan = new Scanner(System.in);
System.out.println("\nMenu\n");
System.out.println("==============================\n\n");
System.out.println("1. Add student to waiting list\n");
System.out.println("2. View waiting list\n");
System.out.println("3. Exit program \n_");
System.out.println("Please enter choice: ");
choice = scan.nextInt();
switch(choice)
{
case 1: myList.Add();
break;
case 2: myList.view();
break;
}
}
while(choice != 3);
}
}
当我输入 1 时,我插入了一个贿赂金额示例:23 当我再次从菜单中输入 2 时,它没有被插入到我的树中,它说,“树是空的”
谢谢