【发布时间】:2017-03-31 10:54:16
【问题描述】:
我需要为大学作业的文本编写 Huffman 压缩程序。 练习分为多个点,其中一个是从给定的TreeNode类型的排序arrayList创建一个二叉树,这个类看起来像这样(我删除了方法体):
public class TreeNode implements Comparable<TreeNode>, Serializable {
private byte value;
private int frequency;
private TreeNode left, right;
/** Creates new TreeNode .. must get initialized with value */
public TreeNode(byte value) {
this(value, 0, null, null);
}
/** Creates new TreeNode with full init */
public TreeNode(byte value, int frequency, TreeNode left, TreeNode right) {
this.value = value;
this.frequency = frequency;
this.left = left;
this.right = right;
public void incFrequency()
public int getFreq()
public Byte getValue()
public TreeNode getLeft()
public TreeNode getRight()
public boolean isLeaf()
public int getSubTreeSize()
public void toHeap(byte[] heap, int myIndex)
public void initLookup(long myCode, int myDepth, Map<Byte, BitCode> lookupTable)
@Override
public int compareTo(TreeNode o)
@Override
public String toString()
public void printSubTree(PrintStream out, int tabs)
public void write(BitStream bs)
public static TreeNode read(BitStream bs)
}
我需要从 TreeNode 类型的 arrayList 创建一棵二叉树,arrayList 按值排序,因此我可以假设具有 smalles 值的元素位于索引位置 0。 树必须满足一个重要条件: 具有下一个较大值的元素需要附加到左侧,具有更大值的元素需要附加到右侧(树将始终构建在右侧)。
我解决这个问题的尝试是遍历列表,获取项目,然后将具有奇数索引的每个项目附加到前一个节点的左叶,并将每个具有偶数索引的项目附加到右叶。
有没有更优雅的方法来解决这个问题? (我不要求你为我做作业,但我可能需要一些想法)
编辑: 我需要保留 SortedList,因为它是练习规范的一部分
【问题讨论】:
-
你的方法有效吗?根据您的描述,它听起来不像(尽管它非常接近会的东西),但是您问题中的措辞使它听起来像它确实有效。
-
@Dukeling 不行
-
尝试在纸上画树,看看应该连接什么。您的方法只需稍作改动即可生效。