struct::tree(n)
β¨ NAME β¨
struct::tree β Create and manipulate tree objects π³β¨
okay so bestie, welcome to the struct::tree(n) manual page from Tcl Data Structures π this one is literally all about trees, and no cap it's iconic. We're gonna build and manipulate tree objects together, periodt.
π 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 π
A tree is a collection of named elements, called nodes, one of which is distinguished as a root π± along with a relation ("parenthood") that places a hierarchical structure on the nodes. (Data Structures and Algorithms; Aho, Hopcroft and Ullman; Addison-Wesley, 1987). In addition to maintaining the node relationships, this tree implementation allows any number of keyed values to be associated with each node. π
The element names can be arbitrary strings. No cap, they can be whatever.
A tree is thus similar to 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. ποΈ
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. β οΈ
β¨ 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. This command may be used to invoke various operations on the tree. It has the following general form:
treeName option ?arg arg ...
Option and the args determine the exact behavior of the command.
If treeName is not specified a unique name will be generated by the package itself. 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
::struct::tree mytree = b
is equivalent to
::struct::tree mytree
mytree = b
and
::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, as it is not a tree method per se. It however interacts tightly with the methodwalk. When used in thewalkscript it causes the traversal to ignore the children of the node we are currently at. This command cannot be used with the traversal modes which look at children before their parent, i.e.postandin. The only applicable orders of traversal arepreandboth. An error is thrown if the command and chosen order of traversal do not fit. π
π¦ TREE OBJECT API π¦
Two general observations beforehand:
- 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, it can be retrieved by calling the methodrootname. π - The method
insertis the only way to create new nodes, and they are automatically added to a parent. A tree object cannot have nodes without a parent, save the root node. π±
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. π³
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. π
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, 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. π§¬treeName append node key valueβ Appends a value to one of the keyed values associated with a node. Returns the new value given to the attribute key. β¨treeName attr key,treeName attr key -nodes list,treeName attr key -glob globpattern,treeName 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.
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?β Return 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 is 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 is returned to the caller. π
Some examples:
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}
}
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]])
()
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. βοΈ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. π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 prefered, and "children -all" will be deprecated sometime in the future. π¦
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 associated command. π₯
treeName exists node
Quick vibe check: does this node even exist in the tree? Returns true if it's there, and that's the whole answer. No cap. β¨
treeName get node key
Hands you the value that's associated with the key key for the node node. Just that one value, bestie. π
treeName getall node ?pattern?
Returns a dictionary of the attribute data for node β and it's literally built to be used with [array set], so go off. π
If you pass the glob pattern, only the attributes whose names match that pattern end up in the dictionary. No pattern? You get the whole thing.
treeName keys node ?pattern?
Returns a list of the keys for node. Give it a pattern and only the attributes whose names match get included in the returned list. And yes, the pattern is a glob pattern. Periodt. π
treeName keyexists node key
Return true if that key exists for node. That's it, that's the whole check. β
treeName index node
Where does node sit in its parent's list of children? This gives you that number. Like, if a node has nodeFoo, nodeBar, and nodeBaz as children, in that order, the index of nodeBar is 1. Count 'em up. π’
treeName insert parent index ?child ?child ...??
Ok bestie, sit down for this one. πͺ
Insert one or more nodes into the tree as children of the node parent. They get added in the order you give them. If parent is root, that means the root of the tree. The new nodes go into the parent's child list at the index given by index. And index can be end, in which case the new nodes land after the current last child β indices of the form "end-n" are accepted too. π
If any of the children you named already exist in treeName, those nodes get moved from their original location to the new location this command points at.
If you don't specify any child, a single node gets added and a name gets generated for it β the generated name is of the form nodex, where x is a number. If you do give names, they must neither contain whitespace nor colons (":"). β οΈ
The return result from this command is a list of the nodes added.
treeName isleaf node
Returns true if node is a leaf of the tree β meaning it has no children β and false otherwise. Living that child-free life. π
treeName lappend node key value
Appends a value (as a list) to one of the keyed values associated with a node. Returns the new value given to the attribute key. Growth mindset. π±
treeName leaves
Return a list containing all the leaf nodes known to the tree. Every end-of-the-branch, all gathered up. π
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. Now listen, lowkey important: this 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, before the re-insertion. That behaviour is what makes it work when you're moving one or more nodes to a different index without changing their parent node. Don't skip that detail, fr fr. π₯
treeName next node
Return the right sibling of node, or the empty string if node was the last child of its parent. No right-hand neighbour, bestie. π
treeName numchildren node
Return the number of immediate children of node. Direct offspring only. β¨
treeName nodes
Return a list containing all the nodes known to the tree. The full roster, no one left out. π
treeName parent node
Return the parent of node. One step up the family tree. β¬οΈ
treeName previous node
Return the left sibling of node, or the empty string if node was the first child of its parent. π
treeName rename node newname
Renames the node node to newname. An error gets thrown if either the node doesn't exist, or a node with the name newname already exists. The result of the command is the new name of the node. Glow-up complete. π
treeName rootname
Returns the name of the root node of the tree. The one at the very top. π
treeName serialize ?node?
Ok this is the big-brain one. π§
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's what lets you, like, transfer tree objects (or parts of them) over arbitrary channels, do persistence, etc. This method is also the basis for both the copy constructor and the assignment operator. Iconic. β¨
The result of this method has to be semantically identical over all implementations of the tree interface. That's literally what will enable us to copy tree data between different implementations of the same interface.
So the result is a list containing a multiple of three elements. Think of it like a serialized array, except there are two values following each key. Those keys are the names of the nodes in the serialized tree. The two values are a reference to the parent node and the attribute data, in that 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 matters, because it gets 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.
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 actually rely on for the structure of the tree is that the root node is signalled 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. 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. Double duty, slay. π«Ά
treeName size ?node?
Return a count of the number of descendants of the node node; if no node is specified, root is assumed. π
treeName splice parent from ?to? ?child?
Insert 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 that are in the range of the indices from and to get 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 gets generated for the new node β the 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 structures. π
treeName unset node key
Removes a keyed value from the node node. And listen β this method will do nothing if the key does not exist. No error, no drama. π
treeName walk node ?-order order? ?-type type? loopvar script
Ok the walk. Let's go. πΆββοΈβ¨
Performs 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:bfsindicates breadth-first,dfsindicates 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:preindicates pre-order,postindicates post-order,bothindicates both-order andinindicates in-order. Pre-order is the default.
Now what do those even mean, bestie:
- Pre-order walking means a parent node is visited before any of its children. So a breadth-first search starting from the root visits the root, then all of the root's children, then 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. It's a generalization of in-order walking for binary trees and it will do the right thing if a binary tree is walked.
- The combination of a breadth-first walk with in-order is illegal. π« Don't do it.
As the walk progresses, the script gets evaluated at each node. That evaluation takes place in the context of the caller of the method. As for loop variables, those are listed in loopvar:
- If only one variable is specified, it will be set to the id of the node.
- When two variables are specified, i.e.
loopvaris 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
enterfor the first evaluation, andleavefor 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 any changes the script makes to the children of that node will immediately influence the walker and the steps it will take. Live, reactive, no cap. π₯
okay so bestie, about touching the tree while you're in the middle of walking it β any other manipulation, like messing with nodes higher up in the tree (i.e. ones you already visited), or doing stuff on the way out, is undefined results territory. They may succeed, error out, silently compute the wrong result, or anything in between. So likeβ¦ unpredictable, and not in a cute way. π
And at last, a tiny little 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. You can use this one inside the walk script to force the command to ignore the children of the node you're currently standing at. But heads up β it will throw an error if the order of traversal is either post or in, because those modes visit the children before their parent, which makes pruning non-sensical. It's giving "why would you even" energy. π
treeName walkproc node ?-order order? ?-type type? cmdprefix
This method is like the method walk in all essentials, except for the interface to your user code. This one 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. Same vibes, different plumbing. π«Ά
π CHANGES FOR 2.0 π
The following noteworthy changes have occurred, bestie. Sit down. π
- 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.
- The methods
keysandgetallnow take an optional pattern argument and will return only attribute data for keys matching this pattern. β¨ - Nodes can now be renamed. See the documentation for the method
rename. slay - 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. π
- The walker API has been streamlined and made more similar to the command
foreach. 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
enteractions 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
- A new method,
attr, was added, allowing the query and retrieval of attribute data without regard to the node relationship. π - The method
childrenhas 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.
Look at us. Creating nodes. Main character energy. π
π 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. We want the tea, fr fr. π«Ά
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. Iykyk. π
π 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 page, bestie β no crumbs left. π This iconic little document comes to you from the source tcllib, version 2.1.1, as the page struct::tree(n). Go forth and build trees. Periodt. π¦πβ¨
π¦ where this page comes from
- fedora 43: tcllib 2.0-3.fc43 Β· TCL
- fedora 44: tcllib 2.0-4.fc44 Β· TCL
- nixos 26.05: tcllib 2.0
- nixpkgs unstable: tcllib 2.0
- 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