-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree_iterator.py
67 lines (55 loc) · 1.91 KB
/
tree_iterator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import logging
from abc import ABC, abstractmethod
from stack import Stack
class TreeIterator(ABC):
def __init__(self, root):
assert root is not None
self._root = root
self._is_there_a_next = True # the root
@abstractmethod
def next(self):
pass
@abstractmethod
def has_next(self):
pass
class Preorder(TreeIterator):
def __init__(self, root):
super().__init__(root)
self._current = self._root
self._stack = Stack()
def next(self):
logging.debug('stack = {}'.format(self._stack))
res = self._current
if self._current.num_children > 0: # parent
for i in range(1, self._current.num_children):
self._stack.push(self._current.children[i])
self._current = self._current.children[0]
else: # leaf
if not self._stack.is_empty():
self._current = self._stack.pop()
else:
self._is_there_a_next = False
return res
def has_next(self):
return self._is_there_a_next
#https://www.techiedelight.com/postorder-tree-traversal-iterative-recursive/
class Postorder(TreeIterator):
def __init__(self, root):
super().__init__(root)
self.root = root
self._stack_in = Stack()
self._stack_out = Stack()
self._fill_stacks()
def _fill_stacks(self):
self._stack_in.push(self._root)
while not self._stack_in.is_empty():
logging.debug('stack_in = {}'.format(self._stack_in))
logging.debug('stack_out = {}'.format(self._stack_out))
current = self._stack_in.pop()
self._stack_out.push(current)
for i in range(current.num_children):
self._stack_in.push(current.children[i])
def next(self):
return self._stack_out.pop()
def has_next(self):
return not self._stack_out.is_empty()