import java.util.*;
import java.lang.*;
import java.io.*;

class Main {
    static class Node {
        Node parent;
        int value;
        Node left;
        Node right;
        public Node(int value) {
            this.value = value;
            this.parent = null;
            this.left = null;
            this.right = null;
        }
    }

    static Node Insert(Node node, int value) {
        if (node == null) {
            return new Node(value);
        } else {
            if (value < node.value) {
                node.left = Insert(node.left, value);
                node.left.parent = node;
            } else if (value > node.value) {
                node.right = Insert(node.right, value);
                node.right.parent = node;
            } 
        }
        return node;
    }
    
    static Node Search(Node node, int value) {
        if (node == null || node.value == value) {
            return node;
        }
        if (value < node.value) return Search(node.left, value);
        // if (value >= node.value) return Search(node.right, value); 
        //이렇게 쓰면 에러남.. return이 없을 수도 있기 때문이라나..
        else return Search(node.right, value);
       
    }
    

    static Node rightRotation(Node root, Node node){
        Node newRoot = node.left;
        
        node.left = newRoot.right; 
        if(newRoot.right != null) {
            newRoot.right.parent = node;
        }

        if(node.parent == null) {
            root = newRoot;
        } else if (node.parent.left == node) {
            node.parent.left = newRoot;
            newRoot.parent = node.parent;
        } else if (node.parent.right == node) {
            node.parent.right = newRoot;
            newRoot.parent = node.parent;
        }

        newRoot.right = node;
        node.parent = newRoot;

        return root;
    }

    static void preOrder(Node node) {
        if (node == null) return;
        System.out.println(node.value);
        preOrder(node.left);
        preOrder(node.right);
    }


    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        StringTokenizer st = new StringTokenizer(br.readLine());
        Node root = null;
        // 1. 트리 생성
        for (int i = 0; i < N; i++) {
            int t = Integer.parseInt(st.nextToken());
            root = Insert(root, t);
        }

        // 2. 회전할 타겟 값 입력
        int a = Integer.parseInt(br.readLine());
        
        // 3. 타겟 노드 탐색 (Search 함수 사용)
        Node targetNode = Search(root, a);

        // 4. 회전 실행 (전체 root와 타겟 노드를 넘기고, 갱신된 root를 돌려받음)
        root = rightRotation(root, targetNode);

        preOrder(root);
    }
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: