Tree

class compas.datastructures.Tree[source]

Bases: Datastructure

A hierarchical data structure that organizes elements into parent-child relationships. The tree starts from a unique root node, and every node (excluding the root) has exactly one parent.

Parameters:
**kwargsdict[str, Any], optional

User-defined attributes of the tree.

Examples

>>> from compas.datastructures import Tree, TreeNode
>>> tree = Tree()
>>> root = TreeNode('root')
>>> branch = TreeNode('branch')
>>> leaf1 = TreeNode('leaf1')
>>> leaf2 = TreeNode('leaf2')
>>> tree.add(root)
>>> root.add(branch)
>>> branch.add(leaf1)
>>> branch.add(leaf2)
>>> print(tree)
<Tree with 4 nodes, 1 branches, and 2 leaves>
>>> tree.print()
<TreeNode root>
    <TreeNode branch>
        <TreeNode leaf2>
        <TreeNode leaf1>
Attributes:
rootcompas.datastructures.TreeNode

The root node of the tree.

nodesgenerator[compas.datastructures.TreeNode]

The nodes of the tree.

leavesgenerator[compas.datastructures.TreeNode]

A generator of the leaves of the tree.

Methods

add

Add a node to the tree.

from_data

Construct an object of this type from the provided data.

get_node_by_name

Get a node by its name.

get_nodes_by_name

Get all nodes by their name.

print_hierarchy

Print the spatial hierarchy of the tree.

remove

Remove a node from the tree.

traverse

Traverse the tree from the root node.

Inherited Methods

ToString

Converts the instance to a string.

copy

Make an independent copy of the data object.

from_json

Construct an object of this type from a JSON file.

from_jsonstring

Construct an object of this type from a JSON string.

sha256

Compute a hash of the data for comparison during version control using the sha256 algorithm.

to_data

Convert an object to its native data representation.

to_json

Convert an object to its native data representation and save it to a JSON file.

to_jsonstring

Convert an object to its native data representation and save it to a JSON string.

validate_data

Validate the data against the object's data schema.