Click to Flip Card

### Trees

What is the starting node of a tree called? Can trees have multiple roots? Can children in a tree have multiple parents?

### Nodes

A tree is a data structure with nodes that are connected by edges. The starting node of a tree is called a root and the nodes at the end are called leaves. Trees always have exactly one root. In trees child nodes must have one parent and edges that are not loops.```
root = {'name': 'A', 'children': []}
node2 = {'name': 'B', 'children': []}
node3 = {'name': 'C', 'children': []}
node4 = {'name': 'D', 'children': []}
node5 = {'name': 'E', 'children': []}
node6 = {'name': 'F', 'children': []}
node7 = {'name': 'G', 'children': []}
node8 = {'name': 'H', 'children': []}
root['children'] = [node2, node3]
node2['children'] = [node4]
node3['children'] = [node5, node6]
node5['children'] = [node7, node8]
print(node3['children'])
"""
[{'name': 'E', 'children':
[{'name': 'G', 'children': []},
{'name': 'H', 'children': []}]},
{'name': 'F', 'children': []}]
"""
```

### Anytree / Render

Using tree data structures is made easy with anytree package.```
from anytree import Node, RenderTree
root = Node('A')
node2 = Node('B', parent=root)
node3 = Node('C', parent=root)
node4 = Node('D', parent=node2)
node5 = Node('E', parent=node3)
node6 = Node('F', parent=node3)
node7 = Node('G', parent=node5)
node8 = Node('H', parent=node5)
print("Tree:")
for pre, fill, node in RenderTree(root):
print(pre, node.name)
# Delete node 'C' and its descendants
node3.parent = None
print("Tree after deletion:")
[print(pre,node.name) for pre,_,node in RenderTree(root)]
"""
Tree:
A
├── B
│ └── D
└── C
├── E
│ ├── G
│ └── H
└── F
Tree after deletion:
A
└── B
└── D
"""
```

Last update: 217 days ago