Given the root of a binary tree, return the inorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3] Output: [1,3,2]
Example 2:
Input: root = [] Output: []
Example 3:
Input: root = [1] Output: [1]
Constraints:
[0, 100].-100 <= Node.val <= 100Follow up: Recursive solution is trivial, could you do it iteratively?
문제 링크: https://leetcode.com/problems/binary-tree-inorder-traversal/
트리 순회 3대장(전위, 중위, 후위) 중 하나인 중위 순회는 "왼쪽 서브트리 → 루트(자기 자신) → 오른쪽 서브트리" 순서로 노드를 방문하는 깊이 우선 탐색(DFS)의 한 종류입니다. 이 순서 때문에, 이진 검색 트리(BST)에 중위 순회를 적용하면 노드 값들이 오름차순으로 정렬되어 나온다는 중요한 특징이 있습니다.
핵심 아이디어: 재귀적으로 왼쪽 끝까지 파고든 후, 돌아오면서 노드를 방문하고, 그 다음 오른쪽으로 이동하는 패턴을 구현한다.
문제의 Follow-up에서 재귀적 풀이와 반복적 풀이를 모두 요구하고 있습니다.
import java.util.ArrayList;
import java.util.List;
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
traverse(root, result);
return result;
}
private void traverse(TreeNode node, List<Integer> list) {
if (node == null) {
return;
}
// 1. 왼쪽 서브트리 순회
traverse(node.left, list);
// 2. 루트 노드 방문
list.add(node.val);
// 3. 오른쪽 서브트리 순회
traverse(node.right, list);
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
while (current != null || !stack.isEmpty()) {
// 1. 가장 왼쪽 노드까지 스택에 담으며 이동
while (current != null) {
stack.push(current);
current = current.left;
}
// 2. 스택에서 노드를 꺼내 방문 (리스트에 추가)
current = stack.pop();
result.add(current.val);
// 3. 오른쪽 서브트리 탐색 준비
current = current.right;
}
return result;
}
}