emory-courses / dsa-java

Data Structures and Algorithms in Java
https://emory.gitbook.io/dsa-java/
42 stars 55 forks source link

[QZ#4] new and old parents #111

Closed MimiOlayeye closed 3 years ago

MimiOlayeye commented 3 years ago

After a single rotation is completed would the grandparent of a node (before the rotation) still be referred to as its grandparent after the rotation or would that change?

Screen Shot 2020-10-12 at 2 42 17 PM

^for example in this image after rotating 5 to the right would 3 still be considered the node's grandparent (like it was before the rotation) or is it now considered to be the node's new parent?

lujiaying commented 3 years ago

If the rotateRight function is defined as https://emory.gitbook.io/dsa-java/binary-search-trees/balanced-bst#rotation

    /**
     * Rotates the specific node to the right.
     * @param node the node to be rotated.
     */
    protected void rotateRight(N node) {
        N child = node.getLeftChild();
        node.setLeftChild(child.getRightChild());

        if (node.hasParent())
            node.getParent().replaceChild(node, child);
        else
            setRoot(child);

        child.setRightChild(node);
    }

And here we conduct rotateRight(5). Then we will get a BST where 4 is parent of 5, and 3 is parent of 4, like the right picture you drew here.