반응형
Binary Search Tree Iterator
Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):
BSTIterator(TreeNode root)Initializes an object of theBSTIteratorclass. Therootof the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.boolean hasNext()Returnstrueif there exists a number in the traversal to the right of the pointer, otherwise returnsfalse.int next()Moves the pointer to the right, then returns the number at the pointer.
Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.
You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.
Example 1:

Input
["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
Output
[null, 3, 7, true, 9, true, 15, true, 20, false]
Explanation
BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);
bSTIterator.next(); // return 3
bSTIterator.next(); // return 7
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 9
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 15
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 20
bSTIterator.hasNext(); // return False
Constraints:
- The number of nodes in the tree is in the range
[1, 105]. 0 <= Node.val <= 106- At most
105calls will be made tohasNext, andnext.
Follow up:
- Could you implement
next()andhasNext()to run in averageO(1)time and useO(h)memory, wherehis the height of the tree?
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class BSTIterator:
def __init__(self, root: Optional[TreeNode]):
self.dt = []
self.idx = 0
self.inorder(root)
def next(self) -> int:
i = self.idx
self.idx += 1
return self.dt[i]
def hasNext(self) -> bool:
return self.idx < len(self.dt)
def inorder(self, root: Optional[TreeNode]) :
if root.left :
self.inorder(root.left)
self.dt.append(root.val)
if root.right :
self.inorder(root.right)
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
inorder 로 돌았을 때 값을 반환하라...
구상이 잘 안되어서 모범답안 참고 했다.
- dt : Inorder 순서대로 담을 리스트
- idx : 현재 노드의 인덱스
- root 를 self.inorder로 넣어서 inorder 진행
next
- 현재 노드 인덱스를 저장해놓고 인덱스를 1 증가
- 현재 노드를 return
hasNext
- 현재 인덱스가 총 길이 보다 작으면 True, 아니면 False = 이렇게 접근하는 건 신선했다.
- 다음 노드가 있냐 없냐로 구분하려고 했는데 이렇게 접근이 되는구나.
inOrder
- 루트노드를 기준으로, 왼쪽 - 루트 - 오른쪽 순으로 진행.
- 왼쪽 노드가 있으면 왼쪽 노드로 진행(방문x), 이때 왼쪽 노드가 루트 노드가 된다.
- 왼쪽 노드가 더 이상 없으면 루트 노드 방문
- 오른쪽 노드가 있으면 오른쪽 노드 진행(방문x), 이때 오른쪽 노드가 루트 노드가 된다.
반응형
'알고리즘 스터디' 카테고리의 다른 글
| [Leetcode/파이썬] 108. Convert Sorted Array to Binary Search Tree (0) | 2026.03.01 |
|---|---|
| [Leetcode/파이썬] 28. Find the Index of the First Occurrence in a String (0) | 2026.03.01 |
| [Leetcode/파이썬] 70. Climbing Stairs (0) | 2026.02.21 |
| [Leetcode/파이썬] 199. Binary Tree Right Side View (0) | 2026.02.21 |
| [Leetcode/파이썬] 121. Best Time to Buy and Sell Stock (0) | 2026.02.13 |