繁体   English   中英

在Java中按级别打印AVL树

[英]Printing an AVL Tree by level in Java

我试图获取一个AVL树并逐级显示它,但是我以某种方式失败了,不知道在哪里。 随附的图片显示了我当前的输出。 我实际上应该得到的是一棵完整的二叉树,因此显然出了点问题。 在所附的图像中,有一张我的“ byLevel”打印功能的照片,因此您可以看到我如何尝试打印它们,并且将附加我的插入功能,因为这是该部分中唯一重要的两个功能。 感谢您的帮助,我不明白自己在做什么错,因为这是一种常用算法。

private Node insert(Node newNode, String newWord){
    if(newNode == null){
        newNode = new Node(newWord);
    }
    else if (newWord.compareToIgnoreCase(newNode.getReservedWord()) < 0){
        newNode.setlChild(insert(newNode.getlChild(), newWord));

        if(depth(newNode.getlChild()) - depth(newNode.getrChild()) == 2){
            if(newWord.compareToIgnoreCase(newNode.getlChild().getReservedWord()) < 0){
                newNode = rotateWithLeftChild(newNode);
            }
            else{
                newNode = doubleWithLeftChild(newNode);
            }
        }
    }
    else if (newWord.compareToIgnoreCase(newNode.getReservedWord()) > 0){
        newNode.setrChild(insert(newNode.getrChild(), newWord));

        if(depth(newNode.getrChild()) - depth(newNode.getlChild()) == 2){
            if(newWord.compareToIgnoreCase(newNode.getrChild().getReservedWord()) > 0){
                newNode = rotateWithRightChild(newNode);
            }
            else{
                newNode = doubleWithRightChild(newNode);
            }
        }
    }
    else;

    newNode.setDepth(max(depth(newNode.getlChild()), depth(newNode.getrChild()) + 1));
    /*if(!this.getAllNodes().contains(newNode)){
        this.getAllNodes().add(newNode);
    }*/
    return newNode;
}

private Node rotateWithLeftChild(Node nodeToRotate){
    Node newNode = nodeToRotate.getlChild();
    nodeToRotate.setlChild(newNode.getrChild());
    newNode.setrChild(nodeToRotate);
    nodeToRotate.setDepth(max(depth(nodeToRotate.getlChild()), depth(nodeToRotate.getrChild()) + 1));
    newNode.setDepth(max(depth(newNode.getlChild()), nodeToRotate.getDepth() + 1));
    return newNode;
}

private Node rotateWithRightChild(Node nodeToRotate){
    Node newNode = nodeToRotate.getrChild();
    nodeToRotate.setrChild(newNode.getlChild());
    newNode.setlChild(nodeToRotate);
    nodeToRotate.setDepth(max(depth(nodeToRotate.getlChild()), depth(nodeToRotate.getrChild()) + 1));
    newNode.setDepth(max(depth(newNode.getrChild()), nodeToRotate.getDepth() + 1));
    return newNode;
}

private Node doubleWithLeftChild(Node nodeToRotate){
    nodeToRotate.setlChild(rotateWithRightChild(nodeToRotate.getlChild()));
    return rotateWithLeftChild(nodeToRotate);
}

private Node doubleWithRightChild(Node nodeToRotate){
    nodeToRotate.setrChild(rotateWithLeftChild(nodeToRotate.getrChild()));
    return rotateWithRightChild(nodeToRotate);
}

TestOutput

再次解决我自己的问题,是的,提供的代码就足够了。 问题很简单,我是通过将+1添加到max函数的第二个而不是在max函数之后添加它来计算深度的。 我认为,由于AVL树是常见的编码,因此这个问题本身就已被充分陈述。 谢谢。

暂无
暂无

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

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