繁体   English   中英

树数据结构中的遍历(按顺序)在 java 中不起作用

[英]Traversal in Tree Data Structure (IN-Order) not working in java

我是数据结构的新手,目前我正在编写树数据结构遍历方法。 现在,当我执行有序遍历时,它应该从较小的值移动到最大值。 但似乎我的方法没有遵循顺序。 我可以知道这里有什么问题吗? 这是代码片段:

    int[] intArr = { 100, 20 ,140, 55, 19, 22, 89, 200, 120 };

    for( int i = 0; i < intArr.length; i++ )
    {
        key += intArr[i];
        tree.insert(key, intArr[i]); // Key is the same as data in this case
        key = "";
    }

    String str = tree.inOrderTraverse();
    System.out.println(str);

输出应该是这样的:19 20 22 55 89 100 120 140 200 但这是实际输出:100 120 140 19 20 200 22 55 89

这是我的递归方法和包装方法:

// SUBMODULE: inOrderTraverse (Wrapper Method)
// IMPORT: none
// EXPORT: (String)
public String inOrderTraverse()
{
    return inOrderRec( root, "" );
}

// SUBMODULE: inOrderRec
// IMPORT: currNd (DSATreeNode), str (String)
// EXPORT: str (String)
private String inOrderRec( DSATreeNode currNd, String str )
{
    if( currNd != null )
    {
        str = inOrderRec( currNd.left, str );
        str += currNd.data + " ";
        str = inOrderRec( currNd.right, str );
    }
    return str;
}

这是我的插入物及其包装纸

// SUBMODULE: insert (Wrapper)
// IMPORT: key (String), data (Object)
// EXPORT: none
public void insert( String key, Object data )
{
    try { root = insertRec( root, key, data ); } // Now root has the address of all the trees 
    catch(IllegalArgumentException e) { System.out.println(e.getMessage()); }
} 

// SUBMODULE: insertRec
// IMPORT: currNd (DSATreeNode), key (String), data (Object)
// EXPORT: updateNd (DSATreeNode)
// ASSERTION: Create the new tree node 
private DSATreeNode insertRec( DSATreeNode currNd, String key, Object data )
{
    DSATreeNode updateNd;
    updateNd = currNd;
    if( currNd == null )
    {
        currNd = new DSATreeNode( key, data );
        updateNd = currNd;
    }
    else if( key.equals(currNd.key) )
        throw new IllegalArgumentException( "Existing key provided" );      // Key must be unique

    else if( key.compareTo(currNd.key) < 0 )
        currNd.left = insertRec( currNd.left, key, data );                  // Recursive to left

    else
        currNd.right = insertRec( currNd.right, key, data );                // Recursive to right

    return updateNd;
}

你的键实际上是字符串。 因此,您将获得插入的键的字典顺序。 这就是为什么输出就是你所看到的。 100 120 140 19 20 200 22 55 89 是正确的字典顺序!

不要使用字符串作为键的数据类型。 如果您的元素是整数,请使用整数。

或者尝试在比较之前将键从字符串转换为整数: Integer.valueOf(key).compareTo(Integer.valueOf(currNd.key))在您的插入方法中。

但这是额外的工作,并且容易出现异常,除非您确定键始终表示整数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM