or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

data-export.mdindex.mdtree-construction.mdtree-modification.mdtree-traversal.mdvisualization.md

index.mddocs/

0

# treelib

1

2

A comprehensive Python library for creating, manipulating, and visualizing hierarchical tree data structures. treelib provides an intuitive API with O(1) node access, multiple traversal algorithms, rich visualization options, and efficient operations for building tree-based applications.

3

4

## Package Information

5

6

- **Package Name**: treelib

7

- **Language**: Python

8

- **Installation**: `pip install treelib`

9

10

## Core Imports

11

12

```python

13

from treelib import Node, Tree

14

```

15

16

## Basic Usage

17

18

```python

19

from treelib import Tree

20

21

# Create a new tree

22

tree = Tree()

23

24

# Build tree structure

25

tree.create_node("Company", "company")

26

tree.create_node("Engineering", "eng", parent="company")

27

tree.create_node("Sales", "sales", parent="company")

28

29

# Add team members

30

tree.create_node("Alice", "alice", parent="eng")

31

tree.create_node("Bob", "bob", parent="eng")

32

tree.create_node("Carol", "carol", parent="sales")

33

34

# Display the tree

35

tree.show()

36

37

# Traverse all nodes

38

for node_id in tree.expand_tree():

39

print(f"Visiting: {tree[node_id].tag}")

40

41

# Find specific nodes

42

eng_team = tree.children("eng")

43

all_employees = [tree[node].tag for node in tree.expand_tree()

44

if tree.level(node) > 1]

45

46

# Export to JSON

47

json_data = tree.to_json()

48

```

49

50

## Architecture

51

52

treelib follows a dual-class architecture optimized for flexibility and performance:

53

54

- **Tree**: Self-contained hierarchical structure managing nodes and relationships with O(1) lookup

55

- **Node**: Elementary objects storing data and maintaining parent-child links across multiple tree contexts

56

57

Key design principles:

58

- Each tree has exactly one root node (or none if empty)

59

- Each non-root node has exactly one parent and zero or more children

60

- Nodes can exist in multiple trees simultaneously with different relationships

61

- All tree operations maintain structural integrity automatically

62

63

## Capabilities

64

65

### Tree Construction and Node Management

66

67

Create trees, add nodes, and build hierarchical structures with automatic relationship management and validation.

68

69

```python { .api }

70

# Tree creation

71

def __init__(tree=None, deep=False, node_class=None, identifier=None): ...

72

73

# Node creation and addition

74

def create_node(tag=None, identifier=None, parent=None, data=None) -> Node: ...

75

def add_node(node, parent=None) -> None: ...

76

77

# Node access

78

def get_node(nid) -> Node | None: ...

79

def __getitem__(key) -> Node: ...

80

def __contains__(identifier) -> bool: ...

81

```

82

83

[Tree Construction](./tree-construction.md)

84

85

### Tree Traversal and Navigation

86

87

Navigate and traverse trees using multiple algorithms including depth-first, breadth-first, and zigzag patterns with filtering and sorting options.

88

89

```python { .api }

90

# Tree traversal

91

def expand_tree(nid=None, mode=DEPTH, filter=None, key=None, reverse=False, sorting=True) -> Iterator[str]: ...

92

def rsearch(nid, filter=None) -> Iterator[str]: ...

93

94

# Structure queries

95

def children(nid) -> list[Node]: ...

96

def parent(nid) -> Node | None: ...

97

def siblings(nid) -> list[Node]: ...

98

def leaves(nid=None) -> list[Node]: ...

99

100

# Tree metrics

101

def size(level=None) -> int: ...

102

def depth(node=None) -> int: ...

103

def level(nid, filter=None) -> int: ...

104

```

105

106

[Tree Traversal](./tree-traversal.md)

107

108

### Tree Modification Operations

109

110

Modify tree structure dynamically with move, remove, copy, and paste operations while maintaining data integrity.

111

112

```python { .api }

113

# Tree modification

114

def move_node(source, destination) -> None: ...

115

def remove_node(identifier) -> int: ...

116

def update_node(nid, **attrs) -> None: ...

117

118

# Tree operations

119

def subtree(nid, identifier=None) -> Tree: ...

120

def remove_subtree(nid, identifier=None) -> Tree: ...

121

def paste(nid, new_tree, deep=False) -> None: ...

122

def merge(nid, new_tree, deep=False) -> None: ...

123

```

124

125

[Tree Modification](./tree-modification.md)

126

127

### Data Export and Import

128

129

Export trees to multiple formats including JSON, dictionaries, and GraphViz DOT for integration with other systems and visualization tools.

130

131

```python { .api }

132

# Data export

133

def to_dict(nid=None, key=None, sort=True, reverse=False, with_data=False) -> dict: ...

134

def to_json(with_data=False, sort=True, reverse=False) -> str: ...

135

def to_graphviz(filename=None, shape="circle", graph="digraph", filter=None, key=None, reverse=False, sorting=True) -> None: ...

136

137

# Tree creation from data

138

@classmethod

139

def from_map(cls, child_parent_dict, id_func=None, data_func=None) -> Tree: ...

140

```

141

142

[Data Export](./data-export.md)

143

144

### Tree Visualization and Display

145

146

Rich tree visualization with customizable display formats, line styles, filtering, and file export capabilities.

147

148

```python { .api }

149

# Tree display

150

def show(nid=None, level=ROOT, idhidden=True, filter=None, key=None, reverse=False,

151

line_type="ascii-ex", data_property=None, stdout=True, sorting=True) -> str | None: ...

152

def save2file(filename, nid=None, level=ROOT, idhidden=True, filter=None, key=None,

153

reverse=False, line_type="ascii-ex", data_property=None, sorting=True) -> None: ...

154

```

155

156

[Visualization](./visualization.md)

157

158

## Constants

159

160

### Tree Traversal Modes

161

162

```python { .api }

163

ROOT = 0 # Tree traversal starting from root level

164

DEPTH = 1 # Depth-first traversal mode

165

WIDTH = 2 # Breadth-first traversal mode

166

ZIGZAG = 3 # Zigzag traversal mode

167

```

168

169

### Node Update Modes

170

171

```python { .api }

172

ADD = 0 # Add child to node

173

DELETE = 1 # Delete child from node

174

INSERT = 2 # Insert child (deprecated, use ADD)

175

REPLACE = 3 # Replace child with another

176

```

177

178

## Node Class

179

180

```python { .api }

181

class Node:

182

def __init__(tag=None, identifier=None, expanded=True, data=None): ...

183

184

# Class constants

185

ADD = 0 # Add child to node

186

DELETE = 1 # Delete child from node

187

INSERT = 2 # Insert child (deprecated, use ADD)

188

REPLACE = 3 # Replace child with another

189

190

# Properties

191

identifier: str # Unique node identifier

192

tag: str # Human-readable display name

193

expanded: bool # Controls visibility in displays

194

data: Any # User-defined payload

195

196

# Relationship query methods

197

def predecessor(tree_id) -> str | None: ...

198

def successors(tree_id) -> list[str]: ...

199

def is_leaf(tree_id=None) -> bool: ...

200

def is_root(tree_id=None) -> bool: ...

201

202

# Relationship management methods

203

def set_predecessor(nid, tree_id) -> None: ...

204

def set_successors(value, tree_id=None) -> None: ...

205

def update_successors(nid, mode=ADD, replace=None, tree_id=None) -> None: ...

206

207

# Tree context management

208

def clone_pointers(former_tree_id, new_tree_id) -> None: ...

209

def reset_pointers(tree_id) -> None: ...

210

def set_initial_tree_id(tree_id) -> None: ...

211

212

# Special methods

213

def __lt__(other) -> bool: ... # Less-than comparison for sorting

214

def __repr__() -> str: ... # Detailed string representation

215

```

216

217

## Exception Classes

218

219

```python { .api }

220

class NodePropertyError(Exception): ... # Base node attribute error

221

class NodeIDAbsentError(NodePropertyError): ... # Node identifier doesn't exist

222

class NodePropertyAbsentError(NodePropertyError): ... # Node data property not specified

223

class MultipleRootError(Exception): ... # Multiple root nodes detected

224

class DuplicatedNodeIdError(Exception): ... # Duplicate node identifier

225

class LoopError(Exception): ... # Circular reference detected

226

class LinkPastRootNodeError(Exception): ... # Invalid root node operation

227

class InvalidLevelNumber(Exception): ... # Invalid level number specified

228

```

229

230

## Common Use Cases

231

232

- **File system representations**: Model directory structures and file hierarchies

233

- **Organizational charts**: Represent company structures and reporting relationships

234

- **Decision trees**: Build algorithmic decision-making structures

235

- **Category taxonomies**: Create classification and tagging systems

236

- **Menu systems**: Design hierarchical navigation interfaces

237

- **Family trees**: Model genealogical relationships and lineage

238

- **Abstract syntax trees**: Parse and represent code structures

239

- **Game trees**: Model game states and move sequences