我在完成这项任务时遇到了一些问题。我目前正在努力解决这个问题。我能够存储和打印值,但是当我打印值时,它只打印我输入的第一个值。任何帮助都会很棒!我真的不太了解递归,它有点让大脑受伤。
package lab6;
import java.util.Scanner;
public class node {
private int value;
static node root;
public node leftLink;
public node rightLink;
public node(int v) {
this.value = v;
}
public int getValue() {
return value;
}
static void traverseShow() {
if (root.leftLink != null) {
root = root.leftLink;
traverseShow();
}
System.out.println(root.getValue());
if (root.rightLink != null) {
root = root.rightLink;
traverseShow();
}
return;
}
static void addNode(node n) {
if (root == null) {
root = n;
} else {
node tmp = root; // save the current root
if (root.getValue() > n.getValue()) {
root = root.leftLink;
addNode(n);
} else if (root.getValue() < n.getValue()) {
root = root.rightLink;
addNode(n);
}
root = tmp; // put the root back to its original value
}
return;
}
public static void main(String[] args) {
int val = 0;
Scanner sc = new Scanner(System.in);
boolean loop = true;
String command = "";
while (loop == true) {
System.out.println("Please enter a command:");
System.out.println("A = insert a new value");
System.out.println("B = display all values");
System.out.println("C = exit program");
command = sc.next();
if (command.equalsIgnoreCase("a")) {
System.out.println("Enter value: ");
val = sc.nextInt();
node newNode = new node(val);
addNode(newNode);
} else if (command.equalsIgnoreCase("b")) {
traverseShow();
} else if (command.equalsIgnoreCase("c")) {
sc.close();
System.exit(0);
} else {
System.out.println("Invalid command! Please try again.");
}
}
}
}