-1
我在处理这个任务时遇到了一些问题。我目前正在试图通过这个工作。我可以存储和打印值,但是当我打印值时,它只打印我输入的第一个值。任何帮助将是惊人的!我实际上对递归知之甚少,它也让脑部受伤。递归二叉树打印错误
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.");
}
}
}
}
您的'node'类不应该有'node root'变量。绝对不应该是静态的。此外,目前还不清楚究竟什么是不起作用的。 –