노드(Node)들이 연결된 계층적인 구조를 가진 비순환적인 그래프
루트 누드가 있는데 이 노드를 제외하면 각 노드는 부모노드와 자식 노드를 가지는데, 각 노드들은 끊어진 연결이 없으며 다른 노드와 사이클을 이루지 않음
→ DB나 알고리즘이 자주 사용 됨
이진 트리(Binary Tree)
모든 노드가 최대 2개의 자식 노드를 갖는 트리
균형 트리(Balanced Tree)
트리의 모든 노드의 깊이 차이가 1 이하인 트리
이진 탐색 트리(Binary Search Tree) BST
이진 트리의 한 종류로, 모든 노드가 아래 조건을 만족해야함
→ 왼쪽 자식 노드는 부모 노드보다 작고, 오른쪽 자식 노드는 부모 노드보다 크다.
class BinarySearchTree {
// 노드 클래스
class Node {
int key;
Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
Node root;
BinarySearchTree() {
root = null;
}
// 삽입 연산
void insert(int key) {
root = insertRec(root, key);
}
Node insertRec(Node root, int key) {
if (root == null) {
root = new Node(key);
return root;
}
if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);
return root;
}
// 탐색 연산
Node search(Node root, int key) {
if (root == null || root.key == key)
return root;
if (root.key > key)
return search(root.left, key);
return search(root.right, key);
}
// 삭제 연산
void delete(int key) {
root = deleteRec(root, key);
}
Node deleteRec(Node root, int key) {
if (root == null) return root;
if (key < root.key)
root.left = deleteRec(root.left, key);
else if (key > root.key)
root.right = deleteRec(root.right, key);
else {
if (root.left == null)
return root.right;
else if (root.right == null)
return root.left;
root.key = minValue(root.right);
root.right = deleteRec(root.right, root.key);
}
return root;
}
int minValue(Node root) {
int minv = root.key;
while (root.left != null) {
minv = root.left.key;
root = root.left;
}
return minv;
}
// 중위 순회 연산
void inorder() {
inorderRec(root);
}
void inorderRec(Node root) {
if (root != null) {
inorderRec(root.left);
System.out.print(root.key + " ");
inorderRec(root.right);
}
}
}
노드와 간선(Edge)으로 구성된 자료구조
노드는 그래프에서 정점(Vertex)이라고도 부름
각 노드는 다른 노드와 연결된 간선을 가지며, 간선은 노드 사이의 관계를 나타냄.
→ 네트워크, 알고리즘, 인공지능 등 에서 사용됨
[간선에 가중치 유무]
import java.util.ArrayList;
import java.util.LinkedList;
public class GraphExample {
private ArrayList<Node> nodes;
public GraphExample() {
nodes = new ArrayList<>();
}
public void addNode(Node node) {
nodes.add(node);
}
public static class Node {
int value;
ArrayList<Node> neighbors;
public Node(int value) {
this.value = value;
neighbors = new ArrayList<>();
}
public void addNeighbor(Node neighbor) {
neighbors.add(neighbor);
}
}
public boolean hasPathDFS(Node source, Node destination) {
if (source == destination) {
return true;
}
for (Node neighbor : source.neighbors) {
if (hasPathDFS(neighbor, destination)) {
return true;
}
}
return false;
}
public boolean hasPathBFS(Node source, Node destination) {
LinkedList<Node> nextToVisit = new LinkedList<>();
boolean[] visited = new boolean[nodes.size()];
nextToVisit.add(source);
while (!nextToVisit.isEmpty()) {
Node node = nextToVisit.remove();
if (node == destination) {
return true;
}
if (visited[node.value]) {
continue;
}
visited[node.value] = true;
for (Node neighbor : node.neighbors) {
nextToVisit.add(neighbor);
}
}
return false;
}
public static void main(String[] args) {
GraphExample graph = new GraphExample();
Node node0 = new Node(0);
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
node0.addNeighbor(node1);
node0.addNeighbor(node2);
node1.addNeighbor(node2);
node2.addNeighbor(node0);
node2.addNeighbor(node3);
node3.addNeighbor(node3);
graph.addNode(node0);
graph.addNode(node1);
graph.addNode(node2);
graph.addNode(node3);
System.out.println(graph.hasPathDFS(node0, node3)); // true
System.out.println(graph.hasPathBFS(node0, node3)); // true
}
}
참고
(트리)
https://www.tutorialspoint.com/data_structures_algorithms/tree_data_structure.htm
https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html
(그래프)
https://www.khanacademy.org/computing/computer-science/algorithms/graph-representation/a/describing-graphs
https://www.geeksforgeeks.org/graph-data-structure-and-algorithms/
https://www.tutorialspoint.com/data_structures_algorithms/graph_data_structure.htm