简体   繁体   English

从文件构造二叉树

[英]Constructing a Binary Tree from a file

I have a Binary Tree file formatted like so: 我有一个二进制树文件,其格式如下:

121
00
99
010
120
011
97
10
98
11

Where it's formatted like (ascii val) over (traversal code). 格式如(ascii val)超过(遍历代码)的位置。 0 = left one, 1 = right one 0 =左一,1 =右一

So the ascii value 121 would be stored in a tree like: 因此,ascii值121将存储在类似以下的树中:

   -1
   /   
 -1       ...
 /
121

How do I construct this properly? 我该如何正确构建?

This is how I am doing it currently: 这是我目前正在做的事情:

TreeNode root;

public Tree(Scanner input){
    while(input.hasNextLine()){
        int ascii = Integer(input.nextLine());
        String code = input.nextLine();
        root = insert(root, ascii, code);
    }
}

public TreeNode insert(TreeNode node, int ascii, String code){
    if(code == ""){
        return new TreeNode(ascii); //treenode is just data, left right
    }

    if(node == null)
        node = new TreeNode(-1);

    char c = code.charAt(0);

    if(c == '0')
        node.left = insert(node.left, ascii, code.substring(1));
    else if(c == '1')
        node.right = insert(node.right, ascii, code.substring(1));

    return node;
}

I do a preorder print, and it looks right, but when i try to decode a huffman-encoded file it does it wrong. 我进行了预打印,看起来不错,但是当我尝试解码霍夫曼编码的文件时,它做错了。 Does anything jump out at you as wrong? 有什么事冒犯你吗? I can post my decode stuff, but it is a little tricky because I am using a custom BitInputStream class that is a little too big to post here. 我可以发布我的解码内容,但这有点棘手,因为我使用的定制BitInputStream类太大了,无法在此处发布。

Check if c is really code you are expecting, if it is not you will just return node. 检查c是否确实是您期望的代码,如果不是,则只返回节点。

if(c == '0')
    node.left = insert(node.left, ascii, code.substring(1));
else if(c == '1')
    node.right = insert(node.right, ascii, code.substring(1));
else
    throw new IllegalArgumentException();

Perhaps it's because you're trying to compare Strings using the == . 也许是因为您试图使用==比较字符串。

== compares whether the references to the object are equal, while the [stringname].equals(otherstring) method compares whether the contents of the two strings are equal. ==比较对象的引用是否相等,而[stringname].equals(otherstring)方法比较两个字符串的内容是否相等。
For example, you have 例如,你有

String code = "hi";
String other = "hi";
code.equals(other);` 
returns true.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM