๐ท๐ผ๋ชจ์ฌ๋ด์ ๊ฐ๋ฐ์์ฒ๐ท๐ผ
์ด์งํธ๋ฆฌ์ํ : ๊น์ด์ฐ์ ํ์(DFS : Depth-fist Search) ๋ณธ๋ฌธ
๊ฐ๋ฐ/์๊ณ ๋ฆฌ์ฆ ๋ฌธ์ ํ์ด JAVA
์ด์งํธ๋ฆฌ์ํ : ๊น์ด์ฐ์ ํ์(DFS : Depth-fist Search)
์์ผ์ด 2021. 7. 27. 01:47๋ฐ์ํ
- ๊ธฐ๋ณธ์ ์ผ๋ก ์ผ์ชฝ์์ ์ค๋ฅธ์ชฝ์ผ๋ก ์ํ
์ ์์ํ : ๋ถ๋ชจ๋ ธ๋๊ฐ ๋งจ ์ ์์น
์ค์์ํ : ๋ถ๋ชจ๋ ธ๋๊ฐ ์ค๊ฐ ์์น
ํ์์ํ : ๋ถ๋ชจ๋ ธ๋๊ฐ ๋งจ ๋ค ์์น
- 2022.01.23
import java.util.*;
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);
DFS(root.rt);
}
// ์ค์์ํ
if(root == null){
return;
}else{
DFS(root.lt);
System.out.print(root.data + " ");
DFS(root.rt);
}
// ํ์์ํ
if(root == null){
return;
}else{
DFS(root.lt);
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);
}
}
- ์ฐ์ต ์ฝ๋
import java.util.*;
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.rt = new Node(6);
tree.DFS(tree.root);
}
}
'๊ฐ๋ฐ > ์๊ณ ๋ฆฌ์ฆ ๋ฌธ์ ํ์ด JAVA' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
์ด์งํธ๋ฆฌ์ํ : ๋์ด์ฐ์ ํ์ - ๋ ๋ฒจํ์(BFS : Breadth-First Search) (0) | 2021.07.30 |
---|---|
๋ถ๋ถ์งํฉ ๊ตฌํ๊ธฐ(DFS) (0) | 2021.07.29 |
[JAVA/์ฝ๋ฉํ ์คํธ] ํผ๋ณด๋์น ์์ด(๋ฉ๋ชจ์ด์ ์ด์ ) (0) | 2021.07.13 |
[JAVA/์ฝ๋ฉํ ์คํธ] ํฉํ ๋ฆฌ์ผ (0) | 2021.07.13 |
[JAVA/์ฝ๋ฉํ ์คํธ] ์ฌ๊ทํจ์๋ฅผ ์ด์ฉํ ์ด์ง์ ์ถ๋ ฅ (0) | 2021.07.13 |
Comments