0

如何确定字母的摩尔斯电码表示?

“E”=“。” “T”=“-”

为什么不是字母?如 let "A" = ".", "B" = "-", "C" =".-" 等等。

我正在尝试为充满这些字母的遍历二叉树开发一种算法。

我的主要目标是搜索一个字母,例如“A”,但我不知道使用什么条件来确定何时分支到右侧或左侧节点。

编辑

这就是我试图做的。在这里,我试图跟踪路径。但是当我用像“E”这样的字母尝试它时,它说根是空的。

static boolean treeContains( Node root, String item ) {
     // Return true if item is one of the items in the binary
         // sort tree to which node points.   Return false if not.
     if ( root == null ) {
           // Tree is empty, so it certainly doesn't contain item.
         System.out.print("Is null");
        return false;
     }
     else if ( item.equals(root.element) ) {
           // Yes, the item has been found in the root node.
        return true;
     }
     else if ( item.compareTo(root.element) < 0 ) {
           // If the item occurs, it must be in the left subtree.
           // So, return the result of searching the left subtree.
        res = res.concat(".");
        return treeContains( root.right, item );
     }
     else {
           // If the item occurs, it must be in the right subtree.
           // So, return the result of searching the right subtree.
        res = res.concat("-");
        return treeContains( root.left, item );
     }
  }  // end treeContains()
4

1 回答 1

2

如果你有一个带有字母的二叉树,那么让左边是一个点 (.),右边是一个破折号 (-)。当您遍历树时,通过跟踪路径,您就知道每个字母的二进制代码是什么。

编辑

查看您的代码,您没有正确遍历树。首先,我不确定变量res是什么,但我敢打赌它是静态的,这不是好的编码习惯。

您真正的问题是您的比较item.compareTo(root.element) < 0不是这棵树的有效比较。相反,您应该使用递归调用作为测试,treeContains( root.right, item ). 只有当这返回 true 时,您才能将点 (.) 附加到您的res字符串。如果它返回 false,那么您可以使用root.left并附加破折号 (-) 进行递归调用。

就个人而言,我会从此方法返回一个字符串。到目前为止,该字符串将是该字母的莫尔斯电码,如果未找到该字母,则为 null。当您从正确的树遍历返回时,构建正确的字符串(您现在用于 res 的字符串)。

要测试的是,您可能必须连接到字符串的前面而不是字符串的后面才能使事情正确。

这棵树的真正用处在于解码莫尔斯电码,将点划线字符串转换为正确的字母。这变成了一个简单的树遍历。

于 2012-11-18T23:53:05.493 回答