有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在java中沿树进行预排序遍历,并打印0和1以对应每个节点上的特定字符?

我已经建立了我的树,每个节点都有一个特定的角色。我希望能够打印每个字符,并在其旁边打印0(左)和1(右),它们对应于特定字符所在的树的路径。所以,如果“a”在树上是左下角。它会打印“a 110”,不幸的是,我无法附上它应该是什么样子的图像,因为这是我问的第一个问题。然而,这里是我目前为止的代码。非常感谢您的帮助

 public static void printCodes(MsgTree root, String code)
  
    if (root == null) {
        return;
    }
    
    printCodes(root.left, code + 1);
    
    printCodes(root.right, code + 1);
    
    System.out.println(root.payloadChar + "    " + code);
}


public static void main(String [] args)
{
    MsgTree tree = new MsgTree("^a^^!^dc^rb");
    
    System.out.println("character   code");
    System.out.println("-------------------------");
    
    printCodes(tree, "0");
    printCodes(tree, "1");
}

共 (2) 个答案

  1. # 1 楼答案

    代码中唯一的错误是,当您在树中移动时,您必须附加到要移动到的代码中,因此您只需更改该行:

    printCodes(root.left, code + "0");
        
    printCodes(root.right, code + "1"); 
    

    此外,您应该通过传递空字符串来调用该方法,因为在根节点中您还没有移动

    printCodes(tree, "");
    
  2. # 2 楼答案

    当您向左移动append0和向右移动append1

    printCodes(root.left, code + "0");
    printCodes(root.right, code + "1");
    

    通过为代码传递空字符串来调用它

    printCodes(tree, "");