[DFS] 9. Tree ๋ง๋จ๋ ธ๋๊น์ง์ ๊ฐ์ฅ ์งง์ ๊ฒฝ๋ก
*์ต๋จ ๊ฑฐ๋ฆฌ๋ ์ฌ์ค์ BFS๋ก ํผ๋ค!!
ํ์ง๋ง ๊ณต๋ถํ๋ ์ ์ฅ์์ BFS๋ก ์๋๋ฅผ ํด๋ณธ๋ค.
<<ํ์ด>>
์ฐ์ Node class๋ฅผ ๋ง๋ ํ ํธ๋ฆฌ๋ฅผ ๋ง๋ค์ด์ค๋ค!
L(Level)์ด 0์ธ ๊ณณ ๋ถํฐ ํด์ DFS๋ฅผ ์์ํ๋ค. ์ด๋ DFS๋ Level๋ฅผ ๋ฐํํ๋ฏ๋ก ํ์ ์ int์ด๋ค.
๋ง์ฝ lt, rt๊ฐ null์ด๋ฉด ๊ทธ ๊ณณ์ด ๋ง๋จ์ด๊ธฐ ๋๋ฌธ์ ๋ฐ๋ก L๋ฅผ ๋ฐํํ๋ค.
๊ทธ๋ ์ง ์์ผ๋ฉด DFS๋ฅผ ์ง์ํ๋๋ฐ Math ๋ด์ฅ ํด๋์ค๋ฅผ ํ์ฉํด์ Math.min(DFS(L + 1, root.lt), DFS(L + 1, root.rt)) ๋ฅผ ํด์ค์ผ๋ก์จ
๋ง๋จ ๋ ธ๋๊น์ง์ ๊ฐ์ฅ ์งง์ ๊ฒฝ๋ก๋ฅผ returnํ๊ฒ ํ๋ค.
*DFS ๊ฐ์ ๊ฒฝ์ฐ ์ผ์ชฝ์ ์๋ DFS๊ฐ ๋จผ์ ๋ค ๊ณ์ฐ ๋ ํ ์ค๋ฅธ ์ชฝ DFS๊ฐ ๊ณ์ฐ ๋๋ค. ์ด๋ฅผ ์๊ฐํ๋ฉฐ ์คํ์ ๊ทธ๋ ค๋ณด๋ฉด์ ๊ณต๋ถ๋ฅผ ๊ณ์ํ์! ๊ทธ๋ฌ๋ค๋ณด๋ฉด DFS์ ์ดํด๋๊ฐ ํ ์ธต ๋ ๊น์ด์ง ๊ฒ์ด๋ค~
class Node {
Node lt, rt;
int data;
public Node(int val) {
data = val;
lt = rt = null;
}
}
class Main {
Node root;
public int DFS(int L, Node root) {
if (root.lt == null && root.rt == null) return L;
else return Math.min(DFS(L+1, root.lt), DFS(L+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));
}
}
์ค๋๋ ๋ฐฐ์๊ฐ๋ค!
'์ฝ๋ฉํ ์คํธ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[DFS] 12. ๊ฒฝ๋กํ์ (1) | 2024.02.08 |
---|---|
[BFS] 10. ๋ง๋จ๋ ธ๋๊น์ง์ ๊ฐ์ฅ ์งง์ ๊ฒฝ๋ก (1) | 2024.02.06 |
[BFS] 8. ์ก์์ง ์ฐพ๊ธฐ (0) | 2024.02.04 |
[BFS] 7. ์ด์งํธ๋ฆฌ ๋ ๋ฒจํ์ (0) | 2024.02.02 |
[DFS] 6. ๋ถ๋ถ ์งํฉ ๊ตฌํ๊ธฐ (0) | 2024.02.02 |
๋๊ธ