계층적 구조를 표현하는 비선형 자료구조
예시
1. 회사 조직도
2. 가족 관계도 등

아래 트리 구조를 코드로 구현하고 출력해보자.
1
/ | \
2 3 4
/ \ |
5 6 7
import java.util.ArrayList;
import java.util.List;
public class TreeConceptPractice {
static class Tree {
int data;
List<Tree> children;
Tree(int data) {
this.data = data;
this.children = new ArrayList<>();
}
void addChild(Tree child) { this.children.add(child); }
}
static void printTree(Tree node, String prefix) {
if (node == null) return;
System.out.println(prefix + node.data);
for (Tree child : node.children) {
printTree(child, prefix + " ");
}
}
static void main(String[] args) {
Tree root = new Tree(1);
Tree n2 = new Tree(2);
Tree n3 = new Tree(3);
Tree n4 = new Tree(4);
Tree n5 = new Tree(5);
Tree n6 = new Tree(6);
Tree n7 = new Tree(7);
root.addChild(n2);
root.addChild(n3);
root.addChild(n4);
n2.addChild(n5);
n2.addChild(n6);
n4.addChild(n7);
printTree(root, "");
}
}
1
2
5
6
3
4
7
printTree(root, "")가 호출되면 "" + 1이 출력된다.
이후 반복문으로 루트(1)의 자식들을 순서대로 순회하는데, 각 자식마다 재귀함수가 실행된다.
1의 자식은 2, 3, 4 순서로 처리되며, 2가 넘어가면 2의 자식인 5, 6이 먼저 출력된다.
2가 끝나면 3, 그다음 4와 4의 자식인 7 순서로 출력된다.