[Algorithm /인프런] 이진트리 순회(넓이우선탐색 : 레벨탐색)

2023. 11. 8. 00:00Algorithm/JAVA

[문제]
아래 그림과 같은 이진트리를 레벨탐색 연습하세요.
1
    2     3
  4  5    6   7

레벨 탐색 순회 출력 : 1 2 3 4 5 6 7


[문제 해결]

package section7_recursive_tree_graph;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

class Node4{
	int data;
	
	Node4 lt, rt;
	public Node4(int val) {
		data = val;
		lt=rt=null;
	}
}
public class levelTree {
	
	Node4 root;
	Stack<Integer> stack = new Stack();
	
	//내 코드
	public void solution(Node4 root) {
		if(root.rt == null)
			return;
		else {
			System.out.print(root.data +" ");
			System.out.print(root.lt.data +" ");
			System.out.print(root.rt.data +" ");
			solution(root.lt);
			solution(root.rt);
		}
	}
	//강의 코드
	public void BFS(Node4 root) {
		Queue<Node4> Q = new LinkedList<>();
		Q.offer(root); // q에 add
		
		//레벨
		int L=0;
		//비어있지 않으면 멈춤
		while(! Q.isEmpty()) {
			int len = Q.size();
			for(int i =0 ; i <len;i++) {
				Node4 cur = Q.poll(); //현재 노드 꺼냄
				System.out.println(cur.data+" ");
				if(cur.lt!= null)Q.offer(cur.lt);//만약 왼쪽 자식 노드가 있다면, 얘를 넣는다
				if(cur.rt!= null)Q.offer(cur.rt);// 만약 오른쪽 자식 노드가 있다면, 얘를 넣는다
			}
			L++; //이게 몇번만에 가는지를 알려줌
			System.out.println();
		}
	}
	public static void main(String[] args) {
		levelTree lvTree= new levelTree(); 
		
		lvTree.root = new Node4(1);
		lvTree.root.lt= new Node4(2);
		lvTree.root.rt= new Node4(3);
		lvTree.root.lt.lt= new Node4(4);
		lvTree.root.lt.rt= new Node4(5);
		lvTree.root.rt.lt= new Node4(6);
		lvTree.root.rt.rt= new Node4(7);
		
		//내꺼 탐색
		lvTree.solution(lvTree.root);
		lvTree.BFS(lvTree.root);
	}
}

 

+) 이건 개인적으로는 구현은 성공했지만、 BFS성질에 따라서 못푼거 같아서 많이 아쉬운 문제。 기본적인 구조를 익혀야겠다고 생각했다。