기타/What I Learned

[TIL] 자료구조 - Rotate 메소드

가죽방패 2022. 8. 3. 09:46

※ Rotate 메소드

- 현재 노드와 부모 노드가 각각 우측 자식인지 좌측 자식인지에 따라 필요한 회전이 달라지는데 각각의 경우는

다음 코드 예시와 같다

 

public void rotate(Node<K, V> node){
	// 현재 노드가 좌측 자식
    if(node.isLeftChild){
    	// 부모 노드가 좌측 자식
        if(node.parent.isLeftChild)
        	// 조부모 노드를 우측회전
            rightRotate(node.parent.parent);
            node.black = false;
            node.parent.black = true;
            if(node.parent.right != null)
            	node.parent.right.black = false;
            return;
        }
        // 부모 노드 우측 자식
        // 조부모 노드 우측-좌측 회전
        rightleftRotate(node.parent.parent);
        node.black = true;
        node.right.black = false;
        node.left.black = false;
        return;
    }