@@ -13,7 +13,8 @@ export Node,
13
13
isleaf,
14
14
islastsibling,
15
15
lastsibling,
16
- prunebranch!
16
+ prunebranch!,
17
+ copy_subtree
17
18
18
19
mutable struct Node{T}
19
20
data:: T
@@ -100,6 +101,50 @@ function addchild(parent::Node{T}, data) where T
100
101
newc
101
102
end
102
103
104
+ """
105
+ child = addchild(parent::Node{T}, data::Node{T}) where {T}
106
+
107
+ Add a node `data` as the last child of `parent`. Requires that `data` is a root node.
108
+ """
109
+ function addchild (parent:: Node{T} , data:: Node{T} ) where T
110
+ if ! isroot (data)
111
+ error (" Child node must be a root node" )
112
+ end
113
+ prevc = parent. child
114
+ if prevc == parent
115
+ parent. child = data
116
+ else
117
+ prevc = lastsibling (prevc)
118
+ prevc. sibling = data
119
+ end
120
+ data. parent = parent
121
+ data
122
+ end
123
+
124
+ """
125
+ new_root = copy_subtree(root::Node{T}) where {T}
126
+
127
+ Get a shallow copy of the subtree rooted at `root`. Note that this does not copy the
128
+ data, and only copies the tree structure.
129
+ """
130
+ function copy_subtree (root:: Node{T} ) where {T}
131
+ new_root = Node {T} (root. data)
132
+ if ! isleaf (root)
133
+ last_child = new_root
134
+ for child in root
135
+ new_child = copy_subtree (child)
136
+ if last_child === new_root
137
+ new_root. child = new_child
138
+ else
139
+ last_child. sibling = new_child
140
+ end
141
+ new_child. parent = new_root
142
+ last_child = new_child
143
+ end
144
+ end
145
+ return new_root
146
+ end
147
+
103
148
"""
104
149
isroot(node)
105
150
@@ -239,7 +284,7 @@ function Base.:(==)(a::Node, b::Node)
239
284
reta, retb = iterate (a), iterate (b)
240
285
while true
241
286
reta === retb === nothing && return true
242
- (reta === nothing ) || (retb === nothing ) && return false
287
+ (( reta === nothing ) || (retb === nothing ) ) && return false
243
288
childa, statea = reta
244
289
childb, stateb = retb
245
290
childa == childb || return false
0 commit comments