【发布时间】:2018-01-28 14:33:06
【问题描述】:
虽然这个问题在别人看来可能根本不是问题,但我被它困住了,我无法解决它。互联网上似乎没有类似的东西。我需要向常规二叉树中的节点添加值。我输入树中的节点数,然后输入根的序号(零)和根中的值,最后输入节点的序号(子节点),子节点的值, 是左孩子还是右孩子的信息,以及父母的序号。最后打印出二叉树。有两个类,一个用于节点,一个用于树(数据成员是根)。代码编译,当我输入节点数时,程序抛出异常 - java.lang.NumberFormatException: For input string: "" 。我被困在这里。这是代码,感谢您的帮助。
import java.util.Scanner;
public class BinaryTreeGeneral {
public static void main( String[] args ) {
Scanner in = new Scanner( System.in );
int N = in.nextInt();
BNode<String> nodes[] = new BNode[N];
BTree<String> tree = new BTree<>();
String[] input = in.nextLine().split(" ");
nodes[Integer.parseInt(input[0])] = new BNode<String>(input[1]);
tree.root = nodes[Integer.parseInt(input[0])];
for (int i = 1; i < N; i++) {
input = in.nextLine().split(" ");
nodes[Integer.parseInt(input[0])] = new BNode<String>(input[1]);
if (input[2].equals("LEFT"))
tree.addNode(nodes[Integer.parseInt(input[3])], BNode.LEFT, nodes[Integer.parseInt(input[0])]);
else
tree.addNode(nodes[Integer.parseInt(input[3])], BNode.RIGHT, nodes[Integer.parseInt(input[0])]);
}
tree.printTreeInorder();
}
}
/*Sample Input:
10
0 10
1 19 LEFT 0
2 8 LEFT 1
3 7 LEFT 2
4 60 RIGHT 2
5 5 RIGHT 1
6 4 RIGHT 0
7 13 RIGHT 6
8 2 LEFT 7
9 1 RIGHT 7*/
另外,我想问一下,这是否是向树的节点添加值的标准方法,还是在实际情况下有更实用、更受欢迎的方法,而不是教科书示例?
【问题讨论】:
-
尝试在
in.nextInt()调用后刻录换行符。比如直接在BTree<String> tree = new BTree<>();之后放in.nextLine()
标签: java tree binary-tree