-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnode_iterator.php
129 lines (118 loc) · 2.53 KB
/
node_iterator.php
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
<?php
require_once(dirname(__FILE__) . '/node.php');
/**
*
* @file node_iterator.php
*
*/
//--------------------------------------------------------------------------------------------------
/**
* @brief
*
* Iterator that visits nodes in a tree in post order. Uses a stack to keep
* track of place in tree.
*
*/
class NodeIterator
{
var $root;
var $cur;
var $stack;
//----------------------------------------------------------------------------------------------
/**
* @brief Takes the root of the tree as a parameter.
*
* @param r the root of the tree
*/
function __construct($r)
{
$this->root = $r;
$this->stack = array();
$this->cur = null;
}
//----------------------------------------------------------------------------------------------
/**
* @brief Initialise iterator and returns the first node.
*
* Initialises the
* @return The first node of the tree
*/
function Begin()
{
$this->cur = $this->root;
while ($this->cur->GetChild())
{
array_push($this->stack, $this->cur);
$this->cur = $this->cur->GetChild();
}
return $this->cur;
}
//----------------------------------------------------------------------------------------------
/**
* @brief Move to the next node in the tree.
*
* @return The next node in the tree, or NULL if all nodes have been visited.
*/
function Next()
{
if (count($this->stack) == 0)
{
$this->cur = NULL;
}
else
{
if ($this->cur->GetSibling())
{
$p = $this->cur->GetSibling();
while ($p->GetChild())
{
array_push($this->stack, $p);
$p = $p->GetChild();
}
$this->cur = $p;
}
else
{
$this->cur = array_pop($this->stack);
}
}
return $this->cur;
}
}
//--------------------------------------------------------------------------------------------------
class PreorderIterator extends NodeIterator
{
//----------------------------------------------------------------------------------------------
function Begin()
{
$this->cur = $this->root;
return $this->cur;
}
//----------------------------------------------------------------------------------------------
function Next()
{
if ($this->cur->GetChild())
{
array_push($this->stack, $this->cur);
$this->cur = $this->cur->GetChild();
}
else
{
while (!empty($this->stack)
&& ($this->cur->GetSibling() == NULL))
{
$this->cur = array_pop($this->stack);
}
if (empty($this->stack))
{
$this->cur = NULL;
}
else
{
$this->cur = $this->cur->GetSibling();
}
}
return $this->cur;
}
}
?>