LeetCode: Binary Search Tree Iterator

이원희·2020년 12월 10일
0

📝 PS

목록 보기
21/65
post-thumbnail

문제 풀이

주어진 BST를 오름차순으로 출력?해주는 문제이다.
next할때마다 다음으로 큰 수를 출력해준다.
hashNext는 다음이 있는지 확인을 한다.

  • BST가 주어지는 BSTIterator()에서 오름차순으로 list에 넣어줬다.
    (오름차순으로 list에 넣는 부분은 이전에 풀었던 문제를 참고했다.)
  • index 변수를 통해 next()와 hasNext()를 구현했다.
import java.util.*;
class BSTIterator {
    List<Integer> list = new ArrayList<>();
    int index = 0;
    
    public BSTIterator(TreeNode root) {
        Stack<TreeNode> s = new Stack<>();
        s.add(root);
        
        while(!s.isEmpty()) {
            TreeNode temp = s.pop();
            if(temp.left != null) {
                TreeNode next = temp.left;
                temp.left = null;
                s.add(temp);
                s.add(next);
                continue;
            }
            if(list.isEmpty()) {
                list.add(temp.val);
            }
            else {
                list.add(temp.val);
            }
            if(temp.right != null) {
                TreeNode next = temp.right;
                temp.right = null;
                s.add(next);
            }
        }
    }
    
    public int next() {
        return list.get(index++);
    }
    
    public boolean hasNext() {
        if(index >= list.size()) {
            return false;
        }
        return true;
    }
}

0개의 댓글