
이진트리( Binary tree )란 모든 노드들이 둘 이하의 자식을 가진 트리이다.

위 그림에서 동그라미를 노드( node )라고 부르면서, 노드는 데이터를 담고 있다.
이진트리는 컴퓨터 응용에서 가장 많이 팔용되는 중요한 트리구조이다.
이진트리의 중요한 점은 왼쪽과 오른쪽의 서브트리를 확실하게 구분한다는 것이고, 모든 노드가 정확하게 두 개의 서브트리를 가지고 있다.




package binaryTree;
public class Node {
private int value;
private Node left;
private Node right;
public Node() {
}
public Node(int value, Node left, Node right) {
this.left = left;
this.right = right;
this.value = value;
}
public int getValue() {
return value;
}
public Node getLeft() {
return left;
}
public Node getRight() {
return right;
}
}
package binaryTree;
import java.util.LinkedList;
import java.util.Queue;
public class BinaryTree {
private Node root;
public BinaryTree(Node root) {
this.root = root;
}
public Node getRoot(){
return root;
}
/*
BFS : 너비 우선 탐색( Breath - First Search )
루트 노드에서 시작해서 인접한 노드를 먼저 탐색하는 방법
주로 두 노드 사이의 최단 경로를 찾고 싶을 때 사용하는 방법이다.
*/
public void printByBFS(Node root) {
Queue<Node> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
Node next = q.poll();
System.out.println(next.getValue()+ " ");
if (next.getLeft() != null) {
q.offer(next.getLeft());
}
if (next.getRight() != null) {
q.offer(next.getRight());
}
}
System.out.println();
}
/*
DFS : 깊이 우선 탐색( DFS, Depth - First Search )
최대한 깊이 내려간 뒤, 더이상 갈 곳이 없으면 옆으로 이동
모든 노드를 방문하고자 하는 경우에 이 방법을 사용하며, BFS보다 간단하지만 검색속도는 BFS보다 느린게 특징
*/
public void printByDFS(Node root) {
if (root == null) return;
printByDFS(root.getLeft());
System.out.println(root.getValue() + " ");
printByDFS(root.getLeft());
}
}
package binaryTree;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@DisplayName("BinaryTree Test")
class BinaryTreeTest {
Node node10 = new Node(10, null, null);
Node node9 = new Node(9, null, null);
Node node8 = new Node(8, node10, null);
Node node7 = new Node(7, null, node9);
Node node6 = new Node(6, node8, null);
Node node5 = new Node(5, null, null);
Node node4 = new Node(4, node7, null);
Node node3 = new Node(3, node5, node6);
Node node2 = new Node(2, node4, null);
Node node1 = new Node(1, node2, node3);
BinaryTree binaryTree = new BinaryTree(node1);
Node root = binaryTree.getRoot();
@Test
void printByBFS() {
System.out.println("root : " + root.getValue());
System.out.println();
System.out.println("==========BFS==========");
binaryTree.printByBFS(root);
}
@Test
void printByDFS() {
System.out.println();
System.out.println("==========DFS==========");
binaryTree.printByDFS(root);
}
}

