class Node {
int data;
Node lt, rt;
public Node(int val) {
this.data = val;
this.lt = null;
this.rt = null;
}
}
public class Main {
Node root;
public static void DFS(Node root) {
if (root == null) return;
else {
System.out.print(root.data + " ");
DFS(root.lt);
DFS(root.rt);
}
}
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);
DFS(tree.root);
}
}
public static void DFS(Node root) {
if (root == null) return;
else {
System.out.print(root.data + " ");
DFS(root.lt);
DFS(root.rt);
}
}
- 전위순회 1 2 4 5 3 6 7 출력
public static void DFS(Node root) {
if (root == null) return;
else {
DFS(root.lt);
System.out.print(root.data + " ");
DFS(root.rt);
}
}
- 중위순회 4 2 5 1 6 3 7 출력
public static void DFS(Node root) {
if (root == null) return;
else {
DFS(root.lt);
DFS(root.rt);
System.out.print(root.data + " ");
}
}
- 후위순회 4 5 2 6 7 3 1 출력
'코딩연습이 좋아서 > 이론이 좋아서' 카테고리의 다른 글
Recursive, Tree, Graph(DFS, BFS 기초) - 이진트리 레벨탐색(BFS : Breadth-First Search) (0) | 2024.12.12 |
---|---|
Recursive, Tree, Graph(DFS, BFS 기초) - 부분집합 구하기(DFS) (0) | 2024.12.12 |
Recursive, Tree, Graph(DFS, BFS 기초) - 피보나치 재귀(메모이제이션) (0) | 2024.12.12 |
Recursive, Tree, Graph(DFS, BFS 기초) - 팩토리얼 (0) | 2024.12.12 |
Recursive, Tree, Graph(DFS, BFS 기초) - 이진수 출력(재귀) (0) | 2024.12.12 |