๐ท๐ผ๋ชจ์ฌ๋ด์ ๊ฐ๋ฐ์์ฒ๐ท๐ผ
Tree ๋ง๋จ๋ ธ๋๊น์ง์ ๊ฐ์ฅ ์งง์ ๊ฒฝ๋ก(DFS, BFS) ๋ณธ๋ฌธ
๊ฐ๋ฐ/์๊ณ ๋ฆฌ์ฆ ๋ฌธ์ ํ์ด JAVA
Tree ๋ง๋จ๋ ธ๋๊น์ง์ ๊ฐ์ฅ ์งง์ ๊ฒฝ๋ก(DFS, BFS)
์์ผ์ด 2021. 8. 1. 17:21๋ฐ์ํ
์๋๋ BFS๋ก ํธ๋ ๋ฌธ์ ์ธ๋ฐ DFS๋ก๋ ํ์ด๋ณธ๋ค.
1. DFS
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 int DFS(int Level, Node root) {
if(root.lt == null && root.rt == null) {
return Level;
}else {
return Math.min(DFS(Level+1, root.lt), DFS(Level+1, 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);
System.out.println(tree.DFS(0, tree.root));
}
}
2. BFS
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 int BFS(Node root) {
Queue<Node> Q = new LinkedList<>();
Q.offer(root);
int Level = 0;
while(!Q.isEmpty()) {
int len=Q.size();
for(int i=0; i<len; i++) {
Node cur = Q.poll();
// ๋ง๋จ๋
ธ๋
if(cur.lt == null && cur.rt == null) {
return Level;
}
if(cur.lt != null) {
Q.offer(cur.lt);
}
if(cur.rt !=null) {
Q.offer(cur.rt);
}
}
Level ++;
}
// ์ฌ๊ธฐ๊น์ง ์์ด
return 0;
}
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);
System.out.println(tree.BFS(tree.root));
}
}
'๊ฐ๋ฐ > ์๊ณ ๋ฆฌ์ฆ ๋ฌธ์ ํ์ด JAVA' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๊ฒฝ๋ก ํ์(์ธ์ ํ๋ ฌ) (0) | 2021.08.02 |
---|---|
๊ทธ๋ํ์ ์ธ์ ํ๋ ฌ (0) | 2021.08.01 |
[JAVA/์ฝ๋ฉํ ์คํธ] ์ก์์ง ์ฐพ๊ธฐ (BFS : ์ํํธ๋ฆฌํ์) (0) | 2021.08.01 |
์ด์งํธ๋ฆฌ์ํ : ๋์ด์ฐ์ ํ์ - ๋ ๋ฒจํ์(BFS : Breadth-First Search) (0) | 2021.07.30 |
๋ถ๋ถ์งํฉ ๊ตฌํ๊ธฐ(DFS) (0) | 2021.07.29 |
Comments