일상용/연습장
[리트코드] 3-5회차
alpakaka
2025. 5. 11. 16:04
연휴도 있었고,, 이런일 저런일 때문에 잠시 소홀했다.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class BSTIterator(object):
def __init__(self, root):
"""
:type root: Optional[TreeNode]
"""
self.stack = list()
self.pushAll(root)
def next(self):
"""
:rtype: int
"""
tmpNode = self.stack.pop()
self.pushAll(tmpNode.right)
return tmpNode.val
def pushAll(self, node):
while node is not None:
self.stack.append(node)
node = node.left
def hasNext(self):
"""
:rtype: bool
"""
return len(self.stack) > 0
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def countNodes(self, root):
"""
:type root: Optional[TreeNode]
:rtype: int
"""
if root is None:
return 0
return self.countNodes(root.left) + self.countNodes(root.right) + 1