从文件构造二叉树

时间:2012-12-02 04:23:31

标签: java binary-tree huffman-code

我有一个二进制树文件格式如下:

121
00
99
010
120
011
97
10
98
11

它的格式如(ascii val)over(遍历代码)。 0 =左一,一=右一

因此ascii值121将存储在树中,如:

   -1
   /   
 -1       ...
 /
121

如何正确构建?

这就是我目前的做法:

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;
}

我做了预购打印,它看起来是正确的,但是当我尝试解码一个霍夫曼编码的文件时,它做错了。有什么事情对你有误吗?我可以发布我的解码内容,但这有点棘手,因为我使用的是一个有点太大的自定义BitInputStream类,无法在此处发布。

2 个答案:

答案 0 :(得分:0)

检查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();

答案 1 :(得分:0)

也许是因为你试图使用==来比较字符串。

==比较对象的引用是否相等,而[stringname].equals(otherstring)方法比较两个字符串的内容是否相等。
例如,你有

String code = "hi";
String other = "hi";
code.equals(other);` 
returns true.
相关问题