struct::tree(3tcl)
π struct::tree β Tcl Data Structures π
okay bestie, welcome to the manual page for struct::tree from Tcl Data Structures. This is the one where we build trees, and no, not the cute little oak outside, the data-structure kind π³β¨
β¨ NAME β¨
struct::tree β Create and manipulate tree objects
πΈ SYNOPSIS πΈ
package require Tcl 8.5 9
package require struct::tree ?2.1.1?
package require struct::list ?1.5?
::struct::tree ?treeName? ?=|:=|as|deserialize source?
treeName option ?arg arg ...?
::struct::tree::prune
treeName = sourcetree
treeName --> desttree
treeName ancestors node
treeName append node key value
treeName attr key
treeName attr key -nodes list
treeName attr key -glob globpattern
treeName attr key -regexp repattern
treeName children ?-all? node ?filter cmdprefix?
treeName cut node
treeName delete node ?node ...?
treeName depth node
treeName descendants node ?filter cmdprefix?
treeName deserialize serialization
treeName destroy
treeName exists node
treeName get node key
treeName getall node ?pattern?
treeName keys node ?pattern?
treeName keyexists node key
treeName index node
treeName insert parent index ?child ?child ...??
treeName isleaf node
treeName lappend node key value
treeName leaves
treeName move parent index node ?node ...?
treeName next node
treeName numchildren node
treeName nodes
treeName parent node
treeName previous node
treeName rename node newname
treeName rootname
treeName serialize ?node?
treeName set node key ?value?
treeName size ?node?
treeName splice parent from ?to? ?child?
treeName swap node1 node2
treeName unset node key
treeName walk node ?-order order? ?-type type? loopvar script
treeName walkproc node ?-order order? ?-type type? cmdprefix
π¦ DESCRIPTION π¦
so a tree is a collection of named elements, and we call those elements nodes. One of them gets singled out as the root, and there's a relation called "parenthood" that stacks all the nodes into a hierarchical structure. (Yes bestie, that's cited: Data Structures and Algorithms; Aho, Hopcroft and Ullman; Addison-Wesley, 1987 π). And on top of keeping all those node relationships straight, this implementation also lets you attach any number of keyed values to every single node. Obsessed.
The element names can be arbitrary strings, so go off, name them whatever.
So a tree is kinda like an array, but with three important differences:
- Trees are accessed through an object command, whereas arrays are accessed as variables. (This means trees cannot be local to a procedure π.)
- Trees have a hierarchical structure, whereas an array is just an unordered collection.
- Each node of a tree has a separate collection of attributes and values. This is like an array where every value is a dictionary. it's giving dictionary-ception π«Ά
Note: The major version of the package struct has been changed to version 2.0, due to backward incompatible changes in the API of this module. Please read the section Changes for 2.0 for a full list of all changes, incompatible and otherwise. Don't skip it, bestie, that's the drama section π
π API π
π TREE CLASS API π
The main commands of the package are:
::struct::tree ?treeName? ?=|:=|as|deserialize source?β this command creates a new tree object with an associated global Tcl command whose name is treeName. That command is your little handle for invoking various operations on the tree. It has this general form:
treeName option ?arg arg ...?
Option and the args determine the exact behavior of the command. periodt.
If treeName isn't specified, a unique name gets generated by the package itself, no stress. If a source is specified, the new tree will be initialized to it. For the operators =, :=, and as, source is interpreted as the name of another tree object, and the assignment operator = will be executed. For deserialize, the source is a serialized tree object and deserialize will be executed.
In other words, this:
::struct::tree mytree = b
is equivalent to:
::struct::tree mytree
mytree = b
and this:
::struct::tree mytree deserialize $b
is equivalent to:
::struct::tree mytree
mytree deserialize $b
::struct::tree::pruneβ this command is provided outside of the tree methods, because it's not really a tree method per se. But it interacts tightly with the methodwalk. When you use it in the walk script, it makes the traversal ignore the children of the node we're currently at π. Lowkey powerful.
β οΈ Heads up bestie: this command cannot be used with the traversal modes that look at children before their parent, i.e.postandin. The only applicable orders of traversal arepreandboth. An error is thrown if the command and the chosen order of traversal don't fit. The vibe check will fail, no cap.
π§ TREE OBJECT API π§
Two general observations beforehand, bestie, write these down:
- The root node of the tree can be used in most places where a node is asked for. The default name of the rootnode is
"root", but this can be changed with the methodrename(see below). Whatever the current name for the root node of the tree is, you can retrieve it by calling the methodrootname. iykyk. - The method
insertis the only way to create new nodes, and they're automatically added to a parent. A tree object cannot have nodes without a parent, save the root node. No orphan nodes allowed, this is a family π«Ά
And now, the methods supported by tree objects created by this package:
treeName = sourcetreeβ this is the assignment operator for tree objects π . It copies the tree contained in the tree object sourcetree over the tree data in treeName. The old contents of treeName are deleted by this operation. gone, reduced to atoms.
This operation is in effect equivalent to:
treeName deserialize [sourcetree serialize]
treeName --> desttreeβ this is the reverse assignment operator for tree objects. It copies the tree contained in the tree object treeName over the tree data in the object desttree. The old contents of desttree are deleted by this operation too.
This operation is in effect equivalent to:
desttree deserialize [treeName serialize]
treeName ancestors nodeβ this method extends the methodparentand returns a list containing all ancestor nodes to the specified node. The immediate ancestor, in other words the parent node, is the first element in that list, its parent the second element, and so on until the root node is reached, making it the last element of the returned list. it's giving family tree reveal π³treeName append node key valueβ appends a value to one of the keyed values associated with an node. Returns the new value given to the attribute key β¨treeName attr keytreeName attr key -nodes listtreeName attr key -glob globpatterntreeName attr key -regexp repattern
This method retrieves the value of the attribute named key, for all nodes in the tree (matching the restriction specified via one of the possible options) and having the specified attribute.
The result is a dictionary mapping from node names to the value of attribute key at that node. Nodes not having the attribute key, or not passing a specified restriction, are not listed in the result. bye, filtered out π
The possible restrictions are:
-nodesβ The value is a list of nodes. Only the nodes mentioned in this list are searched for the attribute.-globβ The value is a glob pattern. Only the nodes in the tree whose names match this pattern are searched for the attribute.-regexpβ The value is a regular expression. Only the nodes in the tree whose names match this pattern are searched for the attribute.
treeName children ?-all? node ?filter cmdprefix?β returns a list of the children of node. If the option-allis specified, then not only the direct children, but their children, and so on are returned in the result π. If a filter command is specified, only those nodes are listed in the final result which pass the test. The command in cmdprefix is called with two arguments: the name of the tree object, and the name of the node in question. It's executed in the context of the caller and has to return a boolean value. Nodes for which the command returns false are removed from the result list before it's returned to the caller.
Some examples, bestie, look at these:
mytree insert root end 0 ; mytree set 0 volume 30
mytree insert root end 1
mytree insert root end 2
mytree insert 0 end 3
mytree insert 0 end 4
mytree insert 4 end 5 ; mytree set 5 volume 50
mytree insert 4 end 6
proc vol {t n} {
$t keyexists $n volume
}
proc vgt40 {t n} {
if {![$t keyexists $n volume]} {return 0}
expr {[$t get $n volume] > 40}
}
and then:
tclsh> lsort [mytree children -all root filter vol]
0 5
tclsh> lsort [mytree children -all root filter vgt40]
5
tclsh> lsort [mytree children root filter vol]
0
tclsh> puts ([lsort [mytree children root filter vgt40]])
()
ate that last one honestly, empty parens, iconic π
treeName cut nodeβ removes the node specified by node from the tree, but not its children. The children of node are made children of the parent of the node, at the index at which node was located. it's a glow-up relocation, not a deletion πtreeName delete node ?node ...?β removes the specified nodes from the tree. All of the nodes' children will be removed as well to prevent orphaned nodes. so be careful bestie, this one takes the whole subtree with it πtreeName depth nodeβ return the number of steps from node node to the root node π³treeName descendants node ?filter cmdprefix?β this method extends the methodchildrenand returns a list containing all nodes descending from node, and passing the filter, if such was specified.
This is actually the same as "treeName children -all". descendants should be preferred, and "children -all" will be deprecated sometime in the future. so switch over now, bestie, future-proof your code π
treeName deserialize serializationβ this is the complement toserializeπ«Ά. It replaces tree data in treeName with the tree described by the serialization value. The old contents of treeName are deleted by this operation.treeName destroyβ destroy the tree, including its storage space and its associated command. it's over, it's done, we don't talk about it anymore π
treeName exists node
Okay so this is a vibe check for nodes π«Ά Returns true if the node node actually exists in the tree. That's it. That's the whole thing. Simple, iconic, done.
treeName get node key
Returns the value associated with the key key for the node node. Just hands you the thing you asked for. π
treeName getall node ?pattern?
Returns a dictionary (and yes bestie, it's the kind that plays nice with [array set]) holding the attribute data for node. If you pass the glob pattern, only the attributes whose names match that pattern show up in the dictionary. No pattern? You get the whole haul. β¨
treeName keys node ?pattern?
Returns a list of keys for node. Specify a pattern and only the attributes whose names match the pattern make it into the returned list. FYI the pattern here is a glob pattern, not a regex, don't get it twisted.
treeName keyexists node key
Returns true if the specified key exists for node. Same energy as exists but for keys instead of nodes. π
treeName index node
Returns the index of node inside its parent's list of children. So like, if a node has nodeFoo, nodeBar, and nodeBaz as children, in that order, then the index of nodeBar is 1. Zero-indexed, no cap. π₯
treeName insert parent index ?child ?child ...??
Inserts one or more nodes into the tree as children of parent, and the nodes get added in the exact order you give them. If parent is root, that refers to the root of the tree. The new nodes land in the parent node's child list at the index you specify.
That index can be end, in which case the new nodes get tacked on after the current last child. Indices of the form "end-n" are accepted too, you're covered. π
Real talk though: if any of the specified children already exist in treeName, those nodes get moved from their original location to the new location this command indicates. Not copied. Moved. Periodt.
If you specify no child at all, a single node gets added and a name gets generated for it. That generated name is of the form nodex, where x is a number. If you do specify names, they must neither contain whitespace nor colons (":"). π«
The return result from this command is a list of the nodes that were added.
treeName isleaf node
Returns true if node is a leaf of the tree (meaning node has no children), and false otherwise. The tree equivalent of "no thoughts, head empty". π
treeName lappend node key value
Appends a value (as a list) to one of the keyed values associated with node. Returns the new value given to the attribute key. Grow your lists, bestie. π±
treeName leaves
Returns a list containing all leaf nodes known to the tree. Every last one. Collect them like PokΓ©mon.
treeName move parent index node ?node ...?
Makes the specified nodes children of parent, inserting them into the parent's child list at the index given by index.
β οΈ Listen up, because this one has a plot twist: the command takes all the nodes out of the tree before inserting them under the new parent, and it figures out the position to place them into after the removal but before the re-insertion.
That behaviour matters, okay? It's important specifically when it comes to moving one or more nodes to a different index without changing their parent node. So if you're reordering siblings, the math is happening on the post-removal list. Ik it's a lot. Write it down. π«Ά
treeName next node
Returns the right sibling of node, or the empty string if node was the last child of its parent. Last child means nobody to your right, sorry girl. π
treeName numchildren node
Returns the number of immediate children of node. Just the count. π
treeName nodes
Returns a list containing all nodes known to the tree. The whole roster.
treeName parent node
Returns the parent of node. Everyone's got one.
treeName previous node
Returns the left sibling of node, or the empty string if node was the first child of its parent. First child = no one on your left, main character energy. π
treeName rename node newname
Renames the node node to newname. An error is thrown if either the node does not exist, or a node with name newname already exists β so no name-stealing in this house. The result of the command is the new name of the node. β¨
treeName rootname
Returns the name of the root node of the tree. Respect the hierarchy. π³
treeName serialize ?node?
This method serializes the sub-tree starting at node. In other words, it returns a tcl value that completely describes the tree starting at node. That means you can, for example, transfer tree objects (or parts of them) over arbitrary channels, do persistence, all that good stuff. This method is also the basis for both the copy constructor and the assignment operator. Slay.
The result of this method has to be semantically identical over all implementations of the tree interface. That's what lets us copy tree data between different implementations of the same interface. It's giving interoperability. π
So, the result is a list containing a multiple of three elements. It's like a serialized array except that there are two values following each key. Those are the names of the nodes in the serialized tree, and the two values are a reference to the parent node and the attribute data, in this order.
The reference to the parent node is the empty string for the root node of the tree. For all other nodes it's the index of the parent node in the list. Which means they're integers, greater than or equal to zero, less than the length of the list, and multiples of three. The order of the nodes in the list is important insofar as it's used to reconstruct the lists of children for each node. The children of a node have to be listed in the serialization in the same order as they're listed in their parent in the tree. No shuffling. π«
The attribute data of a node is a dictionary, i.e. a list of even length containing a serialized array. For a node without attribute data, the dictionary is the empty list.
π Note: while the current implementation returns the root node as the first element of the list, followed by its children and their children in a depth-first traversal, this is not necessarily true for other implementations. The only info a reader of the serialized data can rely on for the structure of the tree is that the root node is signaled by the empty string for the parent reference, that all other nodes refer to their parent through the index in the list, and that children occur in the same order as in their parent.
A possible serialization for the tree structure
+- d
+- a -+
root -+- b +- e
+- c
is
{root {} {} a 0 {} d 3 {} e 3 {} b 0 {} c 0 {}}
The above assumes that none of the nodes have attributes.
treeName set node key ?value?
Set or get one of the keyed values associated with a node. A node may have any number of keyed values associated with it, stack 'em up. If value is not specified, this command returns the current value assigned to the key. If value is specified, this command assigns that value to the key, and returns it. Two-for-one. π
treeName size ?node?
Returns a count of the number of descendants of the node node. If no node is specified, root is assumed. So calling it with no args = size of the whole entire tree. πΈ
treeName splice parent from ?to? ?child?
Inserts a node named child into the tree as a child of the node parent. If parent is root, it refers to the root of the tree. The new node gets added to the parent node's child list at the index given by from. The children of parent which are in the range of the indices from and to are made children of child. If the value of to isn't specified, it defaults to end. If no name is given for child, a name will be generated for the new node β that generated name is of the form nodex, where x is a number. The return result from this command is the name of the new node. π¦
The arguments from and to are regular list indices, i.e. the form "end-n" is accepted as well.
treeName swap node1 node2
Swap the position of node1 and node2 in the tree. Musical chairs but make it data structure. π
treeName unset node key
Removes a keyed value from the node node. The method will do nothing if the key does not exist β no error, no drama, it just quietly does nothing. Ghosting the key, honestly. π»
treeName walk node ?-order order? ?-type type? loopvar script
Perform a breadth-first or depth-first walk of the tree starting at the node node.
The type of walk β breadth-first or depth-first β is determined by the value of type; bfs indicates breadth-first, dfs indicates depth-first. Depth-first is the default.
The order of the walk β pre-, post-, both- or in-order β is determined by the value of order; pre indicates pre-order, post indicates post-order, both indicates both-order and in indicates in-order. Pre-order is the default.
Now the definitions, because this is where it gets juicy:
- Pre-order walking means a parent node is visited before any of its children. For example, a breadth-first search starting from the root will visit the root, followed by all of the root's children, followed by all of the root's grandchildren.
- Post-order walking means a parent node is visited after any of its children.
- Both-order walking means a parent node is visited before and after any of its children.
- In-order walking means a parent node is visited after its first child and before the second. This is a generalization of in-order walking for binary trees and will do the right thing if a binary tree is walked.
π« The combination of a breadth-first walk with in-order is illegal. Do not attempt. It will not go well.
As the walk progresses, the script gets evaluated at each node. That evaluation takes place in the context of the caller of the method. Regarding loop variables, these are listed in loopvar. If only one variable is specified, it'll be set to the id of the node. When two variables are specified β i.e. loopvar is a true list β then the first variable gets set to the action performed at the node, and the other one to the id of the node itself. All loop variables are created in the context of the caller. π«Ά
There are three possible actions: enter, leave, or visit.
enteractions occur during pre-order walks.leaveactions occur during post-order walks.visitactions occur during in-order walks.
In a both-order walk, the command gets evaluated twice for each node; the action is enter for the first evaluation, and leave for the second.
π Note: the enter action for a node is always performed before the walker will look at the children of that node. Which means changes made by the script to the children of the node will immediately influence the walker and the steps it will take. Live updates, bestie. Edit mid-walk. It's giving chaos and I love it. π
okay so bestie, any other manipulation β like of nodes higher in the tree (i.e already visited) or upon leaving β will have undefined results. They may succeed, error out, silently compute the wrong result, or anything in between. π
At last, a small table showing the relationship between the various options and the possible actions:
order type actions notes
----- ---- ----- -----
pre dfs enter parent before children
post dfs leave parent after children
in dfs visit parent between first and second child.
both dfs enter, leave parent before and after children
----- ---- ----- -----
pre bfs enter parent before children
post bfs leave parent after children
in bfs -- illegal --
both bfs enter, leave parent before and after children
----- ---- ----- -----
Note the command ::struct::tree::prune. This command can be used in the walk script to force the command to ignore the children of the node we are currently at. It will throw an error if the order of traversal is either post or in as these modes visit the children before their parent, making pruning non-sensical. π
treeName walkproc node ?-order order? ?-type type? cmdprefix
This method is like method walk in all essentials, except the interface to the user code. This method invokes a command prefix with three additional arguments (tree, node, and action), instead of evaluating a script and passing the node via a loop variable. β¨
β¨ CHANGES FOR 2.0 β¨
The following noteworthy changes have occurred:
[1]β The API for accessing attributes and their values has been simplified. π
All functionality regarding the default attribute "data" has been removed. This default attribute does not exist anymore. All accesses to attributes have to specify the name of the attribute in question. This backward incompatible change allowed us to simplify the signature of all methods handling attributes.
Especially the flag -key is not required anymore, even more, its use is now forbidden. Please read the documentation for the methods set, get, getall, unset, append, lappend, keyexists and keys for a description of the new API's. π
[2]β The methodskeysandgetallnow take an optional pattern argument and will return only attribute data for keys matching this pattern. π[3]β Nodes can now be renamed. See the documentation for the methodrename. βοΈ[4]β The structure has been extended with API's for the serialization and deserialization of tree objects, and a number of operations based on them (tree assignment, copy construction). π¦
Please read the documentation for the methods serialize, deserialize, =, and -->, and the documentation on the construction of tree objects.
Beyond the copying of whole tree objects these new API's also enable the transfer of tree objects over arbitrary channels and for easy persistence. π
[5]β The walker API has been streamlined and made more similar to the commandforeach. In detail:- The superfluous option
-commandhas been removed. ποΈ - Ditto for the place holders. Instead of the placeholders two loop variables have to be specified to contain node and action information. π
- The old command argument has been documented as a script now, which it was in the past too. π
- The fact that enter actions are called before the walker looks at the children of a node has been documented now. In other words it is now officially allowed to manipulate the list of children for a node under these circumstances. It has been made clear that changes under any other circumstances will have undefined results, from silently computing the wrong result to erroring out. β οΈ
- The superfluous option
[6]β A new method,attr, was added allowing the query and retrieval of attribute data without regard to the node relationship. π΅οΈ[7]β The methodchildrenhas been extended with the ability to select from the children of the node based on an arbitrary filtering criterium. Another extension is the ability to look not only at the immediate children of the node, but the whole tree below it. π³
πΈ EXAMPLES πΈ
The following example demonstrates the creation of new nodes:
mytree insert root end 0 ; # Create node 0, as child of the root
mytree insert root end 1 2 ; # Ditto nodes 1 & 2
mytree insert 0 end 3 ; # Now create node 3 as child of node 0
mytree insert 0 end ; # Create another child of 0, with a
# generated name. The name is returned
# as the result of the command.
π«Ά BUGS, IDEAS, FEEDBACK π«Ά
This document, and the package it describes, will undoubtedly contain bugs and other problems. Please report such in the category struct :: tree of the Tcllib Trackers [http://core.tcl.tk/tcllib/reportlist]. Please also report any ideas for enhancements you may have for either package and/or documentation. π
When proposing code changes, please provide unified diffs, i.e the output of diff -u. π
Note further that attachments are strongly preferred over inlined patches. Attachments can be made by going to the Edit form of the ticket immediately after its creation, and then using the left-most button in the secondary navigation bar. π
π KEYWORDS π
breadth-first, depth-first, in-order, node, post-order, pre-order, serialization, tree
π·οΈ CATEGORY π·οΈ
Data structures
Β©οΈ COPYRIGHT Β©οΈ
Copyright (c) 2002-2004,2012 Andreas Kupries <andreas_kupries@users.sourceforge.net>
And that's the whole vibe, bestie! This page is from tcllib 2.1.1 and it's all about struct::tree(3tcl). Go slay with your trees! πβ¨π³
π¦ where this page comes from
- debian trixie: tcllib 2.0+dfsg-4 Β· Tcl
- ubuntu questing: tcllib 2.0+dfsg-4
- ubuntu resolute: tcllib 2.0+dfsg-5 Β· Tcl
- ubuntu stonking: tcllib 2.0+dfsg-6 Β· Tcl
- Copyright (c) 2002-2004,2012 Andreas Kupries <andreas_kupries@users\&.sourceforge\&.net>
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms