본문 바로가기
알고리즘

[LeetCode] 94. Binary Tree Inorder Traversal

by irerin07 2023. 12. 5.
728x90
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> answer = new ArrayList<>();
        
        Stack<TreeNode> stack = new Stack<>();
        
        if (root == null) {
            return answer;
        }
        
        TreeNode current = root;
        
        while(current != null || !stack.isEmpty()) {
            while (current != null) {
                stack.push(current);
                current = current.left;
            }
            
            current = stack.pop();
            answer.add(current.val);
            current = current.right;
        }
        
        return answer;
    }
}

 

Inorder Traversal은

 

Left, Visit, Right의 순서로 기억하면 된다.

728x90