정점과 간선으로 이루어진 집합 class Graph{
private List<List<Integer>> adjList;
public Graph(int vertices) {
adjList = new ArrayList<>(vertices);
for(int i=0; i<vertices; i++){
adjList.add(new ArrayList<>());
}
}
}
정점과 간선 리스트를 정의함
void addEdge(int u, int v){
adjList.get(u).add(v);
adjLsit.get(v).add(u);
}
정점 u, 정점 v를 인접리스트에 추가하여 간선을 추가함
void bfs(int start){
boolean[] visited = new boolean[adjList.size()];
Queue<Integer> queue = new LinkedList<>();
visited[start] = true;
queue.add(start);
while(!queue.isEmpty()){
int node = queue.poll(); // 큐에서 노드를 하나 꺼냄 (FIFO 방식)
System.out.println(node+" ");
for(int neigbor : adjList.get(node)){
if(!visited[neighbor]){
visited[neighbor] = true;
queue.add(neighbor);
}
}
}
}
}
그래프 탐색(BFS)을 구현하여 가까운 노드부터 탐색함

트리의 높이와 레벨

특정 노드부터 특정 노드까지 최단 거리로 갔을 때의 거리루트 노드 ~ 가장 깊은 리프 노드 거리
정이진 트리, 완전 이진 트리, 변질 이진 트리, 포화 이진 트리, 균형 이진 트리 이다.map, set을 구성하는 레드 블랙 트리도 균형 이진 트리의 일종 class Node {
int data; // 노드의 데이터
Node left; // 왼쪽 자식 노드
Node right; // 오른쪽 자식 노드
public Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}
// BinaryTree 클래스: 트리 구현
class BinaryTree {
Node root; // 트리의 루트 노드
// 이진 트리 생성자
public BinaryTree(int rootData) {
root = new Node(rootData);
}
// 트리에 노드 삽입 (이진 탐색 트리 기준)
public void add(Node current, int value) {
if (value < current.data) { // 왼쪽 서브트리에 삽입
if (current.left != null) {
add(current.left, value);
} else {
current.left = new Node(value);
}
} else if (value > current.data) { // 오른쪽 서브트리에 삽입
if (current.right != null) {
add(current.right, value);
} else {
current.right = new Node(value);
}
}
}
// 트리에 노드 추가 (root부터 시작)
public void add(int value) {
add(root, value);
}
// 중위 순회 (Inorder Traversal)
public void inOrderTraversal(Node node) {
if (node != null) {
inOrderTraversal(node.left); // 왼쪽 서브트리 탐색
System.out.print(node.data + " "); // 노드 출력
inOrderTraversal(node.right); // 오른쪽 서브트리 탐색
}
}
// 트리 출력 (중위 순회)
public void printInOrder() {
inOrderTraversal(root);
}
}
public class Main {
public static void main(String[] args) {
// 이진 트리 생성 (루트 노드는 10)
BinaryTree tree = new BinaryTree(10);
// 트리에 노드 삽입
tree.add(5);
tree.add(15);
tree.add(3);
tree.add(7);
tree.add(12);
tree.add(17);
// 트리 중위 순회 출력
System.out.println("이진 트리 중위 순회:");
tree.printInOrder(); // 3 5 7 10 12 15 17 출력
}
}
이진 탐색 트리(BST) | 탐색, 삽입, 제거: 비선형일 경우-O(logn) or 최악(선형)의 경우-O(n)
이러한 BST의 최악의 경우를 방지하고자 AVL 트리와 같은 전략을 세울 수 있음
AVL 트리 | 탐색, 삽입, 삭제: O(logn)