mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 20:26:07 -04:00
Create bst_inorder_iterator.py
This commit is contained in:
parent
abbad25ed8
commit
a2dce9493e
36
trees/bst_inorder_iterator.py
Normal file
36
trees/bst_inorder_iterator.py
Normal file
@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# author: bt3gl
|
||||
|
||||
class Node:
|
||||
def __init__(self, left=None, right=None):
|
||||
self.val = val
|
||||
self.left = left
|
||||
self.right = right
|
||||
|
||||
class BST_Iterator:
|
||||
|
||||
def __init__(self, root: Optional[Node]):
|
||||
|
||||
self.stack = []
|
||||
self.left_inorder(root)
|
||||
|
||||
def left_inorder(self, root):
|
||||
|
||||
while root:
|
||||
self.stack.append(root)
|
||||
root = root.left
|
||||
|
||||
def next(self) -> int:
|
||||
|
||||
top_node = self.stack.pop()
|
||||
|
||||
if top_node.right:
|
||||
self.left_inorder(top_node.right)
|
||||
|
||||
return top_node.val
|
||||
|
||||
def has_next(self) -> bool:
|
||||
|
||||
return len(self.stack) > 0
|
||||
|
Loading…
x
Reference in New Issue
Block a user