【问题标题】:how to print paths to each leaf of binary tree?如何打印到二叉树每个叶子的路径?
【发布时间】:2021-02-13 18:33:13
【问题描述】:

在下面的二叉树中,除了叶子节点之外的所有节点都是空的。我正在尝试将叶子输出到与它旁边的编码表相同的位置。

对于这种方法,这是我所拥有的:

     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 --is-- 010010

c --is-- 0100101

r --is-- 01010

b --is-- 010101


所以我认为我的问题与多余的0有关,如何纠正它?

【问题讨论】:

    标签: java recursion data-structures binary-tree


    【解决方案1】:

    代码正在变异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');
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-26
      • 2016-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      相关资源
      最近更新 更多