<aside> ❓ DFS는 Depth First Search의 약자로 깊이 우선 탐색을 말하고, BFS는 Breath First Search의 약자로 너비 우선 탐색을 말한다.

</aside>

스택(Stack), 큐(Queue), 재귀(Recursive)를 이용

image.png

위의 그림처럼 탐색을 위한 node는 다음과 같이 정의될 수 있다.

class Node {
	int data;
	Node lt, rt;
	
	/* 생성자 */
	public Node(int val) {
		data = val;
		lt = null;
		rt = null;
	}
}

DFS(Depth First Search)

public void DFS(Node root) {
	if(root == null) return;
	else {
		System.out.print(root.data + " ");
		DFS(root.lt);
		DFS(root.rt);
	}
}
// 결과: 0 1 3 4 2 5 6

BFS(Breath First Search)

public void BFS(Node root) {
	Queue<Node> q = new LinkedList<>();
	
	q.offer(root);
	int L = 0; // Level
	
	while(!q.isEmpty()) {
		int len = q.size();
		System.out.println(L + " : ");
		
		for(int i=0; i<len; i++) {
			Node current = q.poll();
			System.out.println(current.data + " ");
			if(current.lt != null) {
				q.offer(current.lt);
			}
			if(current.rt != null) {
				q.offer(current.rt);
			}
		}
		
		L++;
		System.out.println();
	}
}
// 0 : 0
// 1 : 1 2
// 2 : 3 4 5 6

⭐DFS/BFS in Programmers

프로그래머스에 있는 DFS/BFS 문제들

타켓 넘버