Scribbling

LeetCode: 173. Binary Search Tree Iterator 본문

Computer Science/Algorithms & Data Structures

LeetCode: 173. Binary Search Tree Iterator

focalpoint 2023. 9. 30. 02:43

https://leetcode.com/problems/binary-search-tree-iterator/description/?envType=study-plan-v2&envId=top-interview-150 

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

Python Code with yield

# 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.root = root
        def generator(node):
            if node.left is not None:
                yield from generator(node.left)
            yield node.val
            if node.right is not None:
                yield from generator(node.right)
        self.generator = generator(self.root)
        self.nxt = next(self.generator, None)

    def next(self) -> int:
        ret = self.nxt
        self.nxt = next(self.generator, None)
        return ret

    def hasNext(self) -> bool:
        return self.nxt is not None

# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()