코딩연습이 좋아서/이론이 좋아서
Recursive, Tree, Graph(DFS, BFS 기초) - 이진트리순회(DFS : Depth-First Search)
zoaseo
2024. 12. 12. 15:39
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 출력