Because in-order traverse BST can generate a ascending sequence.
# 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: TreeNode):
def inorder(node):
if node:
yield from inorder(node.right)
yield node.val
yield from inorder(node.left)
self.nodes = list(inorder(root))
def next(self) -> int:
return self.nodes.pop()
def hasNext(self) -> bool:
return self.nodes
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
A stack based iterative solution
# 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: TreeNode):
self.stack = [root] if root else []
def next(self) -> int:
node = self.stack[-1]
while node.left:
self.stack.append(node.left)
tmp = node.left
node.left = None
node = tmp
# pop the parent node
self.stack.pop()
if node.right:
self.stack.append(node.right)
node.right = None
return node.val
def hasNext(self) -> bool:
return self.stack
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
Edited on 04/22/2021. Refactor the recursive and iterative solution.
No comments:
Post a Comment