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

์ด์ง„ํŠธ๋ฆฌ์ˆœํšŒ : ๋„“์ด์šฐ์„ ํƒ์ƒ‰ - ๋ ˆ๋ฒจํƒ์ƒ‰(BFS : Breadth-First Search) ๋ณธ๋ฌธ

๊ฐœ๋ฐœ/์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œํ’€์ด JAVA

์ด์ง„ํŠธ๋ฆฌ์ˆœํšŒ : ๋„“์ด์šฐ์„ ํƒ์ƒ‰ - ๋ ˆ๋ฒจํƒ์ƒ‰(BFS : Breadth-First Search)

์š”์ผ์ด 2021. 7. 30. 11:50
๋ฐ˜์‘ํ˜•

Stack์„ ์‚ฌ์šฉํ•˜๋Š” DFS(๊นŠ์ด์šฐ์„ ํƒ์ƒ‰)๊ณผ ๋‹ค๋ฅด๊ฒŒ BFS(๋„“์ด์šฐ์„ ํƒ์ƒ‰)์€ Queue๋ฅผ ์‚ฌ์šฉํ•˜๋ฉฐ ๊ฐ ๋…ธ๋“œ ์œ„์น˜์—๋”ฐ๋ผ Level์„ ์ •ํ•˜์—ฌ ํƒ์ƒ‰ํ•œ๋‹ค.

 

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 BFS(Node root) {
		Queue<Node> Q = new LinkedList<>();
		Q.offer(root);
		int Level = 0;
		while(!Q.isEmpty()) {
			 int len = Q.size();
			 System.out.print(Level + " : ");
			 for(int i=0; i<len; i++) {
				 Node cur = Q.poll();
				 System.out.print(cur.data + " ");
				 if(cur.lt!=null) {
					 Q.offer(cur.lt);
				 }
				 if(cur.rt != null) {
					 Q.offer(cur.rt);
				 }
			 }
			 Level++;
			 System.out.println();
		}
	}
	
	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.BFS(tree.root);
	
	}
}
Comments