使用JAVA按字母顺序构建字符串的BST

问题描述 投票:0回答:0

预期输出: HAR@提卡#100 HAR@misty#102 HAR@litfried#101 HAR@grant#104 HAR@甲虫#103

实际产量 HAR@提卡#100 HAR@misty#101 HAR@litfried#102 HAR@grant#103 HAR@甲虫#104 节点遍历和插入

//insert a node
public void insertColleague(Colleague c) {
    if (root == null) {
        root = new BSTNode(c);
    } else{
        insertCRecurse(root, c);
    }
}

//recursively insert node function
private void insertCRecurse(BSTNode currNode, Colleague c) {
    if (c.getUserName().compareToIgnoreCase(currNode.getC().getUserName())<1){
        if (currNode.getL() != null){
            insertCRecurse(currNode.getL(), c);
        } else{
            currNode.setL(new BSTNode(c));
        }
    }else {
        if (currNode.getR() !=null){
            insertCRecurse(currNode.getR(), c);
        } else{
            currNode.setR(new BSTNode(c));
        }
    }

}

//traverse the tree in-order
public void printInOrder() {
    printInOrderRecursive(root);
}

private void printInOrderRecursive(BSTNode current) {
    if (current == null) {
        System.out.print("<null>");
        return;
    }
    System.out.print("(E: " + current.getC().getUserName() + " ");
    System.out.print("L: ");
    printInOrderRecursive(current.getL());
    System.out.print(" R: ");
    printInOrderRecursive(current.getR());
    System.out.print(")");
}

public String printReverseAlphabetic(){
    StringBuilder sb = new StringBuilder();
    printReverseAlphabeticHelper(root, sb);
    return sb.toString();
}

private void printReverseAlphabeticHelper(BSTNode node, StringBuilder sb){
    if (node == null){
        return;
    }

    printReverseAlphabeticHelper(node.getR(), sb);
    sb.append(node.getC().getUniqueUserName()).append("\n");
    printReverseAlphabeticHelper(node.getL(), sb);
}

}

用户名实现生成唯一的用户名。这些是我认为错误可能是因为树遍历以正确的顺序出现但我只是不知道如何修复错误。

public String getUserName(){
    String userName = "HAR@" + tag; //sets username
    return userName;
}

public String getUniqueUserName(){
    return generateUNN();
}

private String generateUNN(){
    String unnN = "#" + String.format("%03d", unnNum++);
    return this.getUserName()+unnN;
}
java binary-search-tree reverse stringbuilder suffix-tree
© www.soinside.com 2019 - 2024. All rights reserved.