
난이도: ★☆☆☆☆ • solved on: 2025-12-07

data 값을 삽입한 뒤 root 노드 전체를 반환해야 한다.자료구조
Node : data, left, right를 가지는 기본 트리 구조알고리즘/기법
BST 규칙:
data < node.data → 왼쪽 이동data > node.data → 오른쪽 이동재귀 또는 반복 기반 삽입
핵심 키워드
root == null인 경우 초기 트리를 만드는 상황이므로new Node(data)반환.그렇지 않으면
currentNode를 루트부터 따라 내려가며:
data > currentNode.data→ 오른쪽으로 이동data <= currentNode.data→ 왼쪽으로 이동해당 위치에 자식이 없으면 새 노드를 삽입하고 전체 트리의 root 반환.
current = root
while (current != null):
if data < current.data:
왼쪽이 null이면 삽입 후 종료
아니면 왼쪽으로 계속 이동
else:
오른쪽이 null이면 삽입 후 종료
아니면 오른쪽으로 이동
public static Node insert(Node root, int data) {
if (root == null) {
return new Node(data);
}
Node currentNode = root;
while (currentNode != null) {
if (currentNode.data < data) {
if (currentNode.right == null) {
currentNode.right = new Node(data);
return root;
}
currentNode = currentNode.right;
continue;
}
if (data <= currentNode.data) {
if (currentNode.left == null) {
currentNode.left = new Node(data);
return root;
}
currentNode = currentNode.left;
continue;
}
}
return root;
}
root == null)을 반드시 고려해야 한다.null 케이스 없으면 실패한다.재귀를 쓰면 코드를 크게 줄이면서 BST 삽입 규칙을 그대로 표현할 수 있다.
root == null이면 삽입 위치 도달 → new Node(data) 반환.data < root.data → 왼쪽 서브트리에 삽입.data > root.data → 오른쪽 서브트리에 삽입.if root == null → 새 노드 생성
if data < root.data → root.left = insert(root.left, data)
if data > root.data → root.right = insert(root.right, data)
return root
public static Node insert(Node root, int data) {
if (root == null) {
return new Node(data);
}
if (data <= root.data) {
root.left = insert(root.left, data);
} else {
root.right = insert(root.right, data);
}
return root;
}
| 방법 | 시간 복잡도 | 공간 복잡도 |
|---|---|---|
| 방법 1(반복문) | 평균 O(h), 최악 O(N) | O(1) |
| 방법 2(재귀) | 평균 O(h), 최악 O(N) | O(h) (재귀 스택) |
(h는 트리 높이, N은 전체 노드 수)
root가 처음에는 null이며, 삽입 요청을 반복 호출해 트리를 구성한다는 점을 알기 전까지 root == null 케이스를 고려하지 못했다.while(true) 보다는 빠른 반환(return) 패턴이 더 깔끔하게 동작한다.