【问题标题】:Entering values to nodes in a binary tree向二叉树中的节点输入值
【发布时间】: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&lt;String&gt; tree = new BTree&lt;&gt;();之后放in.nextLine()

标签: java tree binary-tree


【解决方案1】:

问题是您在不完全了解它们的作用的情况下混合了 nextIntnextLine

  • nextInt 方法提取下一个标记并将其解析为整数。
  • nextLine 最多读取(包括)下一个行尾标记,并在删除行尾的情况下返回它。

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

解决方案包括:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    相关资源
    最近更新 更多