向二叉树中的节点输入值

Entering values to nodes in a binary tree

虽然这个问题在别人看来根本不是问题,但我就是死缠烂打,无法解决。互联网上似乎没有类似的东西。我需要向常规二叉树中的节点添加值。我正在输入树中的节点数,然后我输入根的序号(零)和根中的值,最后,我输入节点的序号(child), child 的值、左或右 child 的信息以及 parent 的序号。最后打印二叉树。有两个类,一个是节点,一个是树(数据成员是root)。代码编译,当我输入节点数时,程序抛出异常 - 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*/

此外,我想问一下,这是否是向树的节点添加值的标准方法,或者在实际情况下是否有更实用、更受欢迎的方法,而不是教科书示例?

问题是您混合了 nextIntnextLine,但没有完全理解它们的作用。

  • nextInt 方法提取下一个标记并将其解析为整数。
  • nextLine 读取(并包括)下一个行尾标记,然后 return 删除行尾标记。

所以...如果您调用 nextIntnextLine 为包含一个数字的行,那么 nextLine() 调用将 return 一个空字符串. (如果你不明白我在说什么,请仔细阅读这两种方法的javadocs。)

解决方案包括:

  1. nextInt() 之后添加一个 nextLine() 调用以消耗该行的其余部分。
  2. 停止使用 nextLine()split(...),只使用 nextInt()next() 调用。
  3. 第一行也使用 nextLine().split(...)