问题描述
在下面的二叉树中,除叶节点外,所有节点均为空。我正在尝试将叶子输出到它旁边的编码表。
对于这种方法,这就是我所拥有的:
public static void printCodes(MsgTree root,String encoding) {
if (root.left == null && root.right == null) {
System.out.println(root.payloadChar + " --is-- " + encoding);
} else {
if (root.left != null) {
encoding += '0';
printCodes(root.left,encoding);
} if(root.right!=null) {
encoding += '1';
printCodes(root.right,encoding);
}
}
}
但是,这是我得到的输出:
a --is-- 0
! -是-0100
d-是-010010
c-是-0100101
r-是-01010
b-是-010101
所以我认为我的问题与多余的0有关,如何解决?
解决方法
代码正在突变encoding
,因此,如果有两个子代,则转到左侧节点将保留0
。
例如,您可以将encoding
保持不变:
public static void printCodes(MsgTree root,String encoding) {
if (root.left == null && root.right == null) {
System.out.println(root.payloadChar + " --is-- " + encoding);
} else {
if (root.left != null) {
printCodes(root.left,encoding + '0');
} if (root.right!=null) {
printCodes(root.right,encoding + '1');
}
}
}