ALGORITHM

[JAVA] 알고리즘 : DFS- 이진트리순회

연듀 2022. 8. 15. 10:25

 

 

 

 

 

class Node{
    int data;
    Node lt, rt; // 인스턴스 변수-노드라는 클래스의 객체 주소를 저장
    public Node(int val){
        data=val;
        lt=rt=null;
    }
}

public class Main{
    Node root;
    public void DFS(Node root){
        if(root==null) return; // 말단 노드라면
        else{
            // System.out.print(root.data+" "); // 전위 순회
            DFS(root.lt);
            // System.out.print(root.data+" "); // 중위 순회
            DFS(root.rt);
            // System.out.print(root.data+" "); // 후위 순회
        }
    }
    public static void main(String[] args) {
        Main tree=new Main();
        tree.root=new Node(1);
        tree.root.lt=new Node(2);
        tree.root.rt=new Node(3);
        tree.root.lt.lt=new Node(4);
        tree.root.lt.rt=new Node(5);
        tree.root.rt.lt=new Node(6);
        tree.root.rt.rt=new Node(7);
        tree.DFS(tree.root);
    }
}