1) 주어진 BST를 inorder로 순회하여 ArrayList에 넣는다.
2) next()는 ArrayList의 인덱스 0 에 있는 데이터를 반환하고 삭제한다.
3) hasNext()는 ArrayList가 비어있다면 전부 next()해서 가져간 것이므로, false를 반환한다.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class BSTIterator {
List<Integer> list = new ArrayList<Integer>();
public BSTIterator(TreeNode root) {
inorder(root);
}
public void inorder(TreeNode node) {
if(node != null) {
inorder(node.left);
list.add(node.val);
inorder(node.right);
}
}
public int next() {
int nextVal = list.get(0);
list.remove(0);
return nextVal;
}
public boolean hasNext() {
if(!list.isEmpty())
return true;
else
return false;
}
}
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator obj = new BSTIterator(root);
* int param_1 = obj.next();
* boolean param_2 = obj.hasNext();
*/
'JAVA > leetcode' 카테고리의 다른 글
[LeetCode Medium] BST - Insert into a Binary Search Tree (0) | 2021.08.10 |
---|---|
[LeetCoed] BST - Search in a Binary Search Tree (0) | 2021.08.10 |
[LeetCode Medium] BST - Validate Binary Search Tree !! (0) | 2021.08.10 |
[LeetCode] Two Sum II - Two Pointer (0) | 2021.08.09 |
[LeetCode] Array Partition I (0) | 2021.08.09 |