::자료구조:: 기본1(이진트리)

MinJeongKim·2024년 9월 24일
0
package tree;

public class Node {
    int dat;
    Node leftChild, rightChild;

    public Node(int dat) {
        this.dat = dat;
    }
}
package tree;
import tree.Node;

/* 이진트리 */
public class binaryTree {
    public static void main(String[] args) {

        int count = 7;

        Node[] nodes = new Node[count + 1];

        for(int i = 1; i <= count; i++) {
            Node binaryTree = new Node(i);
            nodes[i] = binaryTree;
        }

        for (int i = 1; i <= count; i++) {
            if(i * 2 <= count) {
                nodes[i].leftChild = nodes[i * 2];
                nodes[i].rightChild = nodes[(i * 2) + 1];
            }
        }
        // 전위
        preOrder(nodes[1]);
        System.out.println();

        // 중위
        inOrder(nodes[1]);
        System.out.println();

        // 후위
        postOrder(nodes[1]);
    }

    static void preOrder(Node node) {
        if(node != null) {
            System.out.print(node.dat + " ");
            preOrder(node.leftChild);
            preOrder(node.rightChild);
        }
    }


    static void inOrder(Node node) {
        if(node != null) {
            inOrder(node.leftChild);
            System.out.print(node.dat + " ");
            inOrder(node.rightChild);
        }
    }


    static void postOrder(Node node) {
        if(node != null) {
            postOrder(node.leftChild);
            postOrder(node.rightChild);
            System.out.print(node.dat + " ");
        }
    }
}

출처 https://www.youtube.com/watch?v=lq85zEW1S_s&t=587s
profile
웹 개발자 & DA

0개의 댓글

관련 채용 정보