반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 173 | Binary Search Tree Iterator | Python 본문
728x90
반응형
문제 링크: https://leetcode.com/problems/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 the BSTIterator class. The root of 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() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.
- 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.
조건
- The number of nodes in the tree is in the range [1, $10^5$].
- 0 <= Node.val <= $10^6$
- At most 105 calls will be made to hasNext, and next.
내 풀이
Kth Smallest Element in a BST문제처럼 제일 작은 노드부터 차례로 탐색한다. (inorder 함수)
그러면 self.arr에 오름차순으로 정리된다.
이제 next나 hasnext는 self.arr로 구현하면 된다.
코드
# 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.arr = []
self.cur = -1
def inorder(root):
if root:
inorder(root.left)
self.arr.append(root.val)
inorder(root.right)
inorder(root)
def next(self) -> int:
self.cur += 1
return self.arr[self.cur]
def hasNext(self) -> bool:
return True if self.cur+1 < len(self.arr) else False
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
728x90
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 706 | Design HashMap | Python (0) | 2022.04.22 |
---|---|
[LeetCode] 705 | Design HashSet | Python (0) | 2022.04.21 |
[LeetCode] 99 | Recover Binary Search Tree | Python (0) | 2022.04.19 |
[LeetCode] 230 | Kth Smallest Element in a BST | Python (0) | 2022.04.18 |
[LeetCode] 669 | Trim a Binary Search Tree | Python (0) | 2022.04.15 |
Comments