๐ŸŒท๐ŸŒผ๋ชจ์—ฌ๋ด์š” ๊ฐœ๋ฐœ์˜์ˆฒ๐ŸŒท๐ŸŒผ

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));
	}
}
Comments