파비의 매일매일 공부기록

Today's Challenge 본문

Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 4. 20. 23:45

https://leetcode.com/problems/binary-search-tree-iterator/

 

Binary Search Tree Iterator - LeetCode

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

inorder 순회하는 class를 만드는 걸로 보인다.
python으로 작성한 다른 사람의 코드를 보니 Generator를 사용해서 풀었는데,
실무에서는 Generator를 거의 사용 안 해서 처음엔 이게 뭔가.. 했다.

yield 키워드를 사용하게 되는데
이걸 호출하면 암시적으로 return이 호출되고, 그다음 호출하면 다음의 yield 코드가 실행되는 개념이다.

결국 _inorder내에서 _inorder를 재호출하게 되니까 중위순위 동작을 하게 된다.
소스는 다음과 같다.

class BSTIterator:
    
    def __init__(self, root: Optional[TreeNode]):
        self.iter = self._inorder(root)
        self.n = next(self.iter, None)
        
    def _inorder(self, node: Optional[TreeNode]) -> Generator[int, None, None]:
        if node:
            yield from self._inorder(node.left)
            yield node.val
            yield from self._inorder(node.right)
        

    def next(self) -> int:
        res, self.n = self.n, next(self.iter, None)
        return res

    def hasNext(self) -> bool:
        return self.n is not None
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

Today's Challenge  (0) 2022.04.23
Today's Challenge  (0) 2022.04.22
Today's Challenge  (0) 2022.04.21
Today's Challenge  (0) 2022.04.19
Today's Challenge  (0) 2022.04.18
Comments