arborikit 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Arborikit contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.4
2
+ Name: arborikit
3
+ Version: 0.1.0
4
+ Summary: General trees, unbalanced BSTs and red-black trees. Zero dependencies.
5
+ Author: Arborikit contributors
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/jojo8356/arborikit
8
+ Project-URL: Repository, https://github.com/jojo8356/arborikit
9
+ Project-URL: Issues, https://github.com/jojo8356/arborikit/issues
10
+ Project-URL: Changelog, https://github.com/jojo8356/arborikit/blob/main/CHANGELOG.md
11
+ Keywords: tree,bst,red-black,arn,abt,arbre,data-structure,algorithm
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Education
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.8
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Topic :: Education
25
+ Classifier: Topic :: Software Development :: Libraries
26
+ Classifier: Typing :: Typed
27
+ Requires-Python: >=3.8
28
+ Description-Content-Type: text/markdown
29
+ License-File: LICENSE
30
+ Provides-Extra: test
31
+ Requires-Dist: pytest>=7; extra == "test"
32
+ Dynamic: license-file
33
+
34
+ # arborikit (Python)
35
+
36
+ > Arbres généralistes, ABR non équilibrés et ARN — **zéro dépendance**.
37
+
38
+ ```python
39
+ from arborikit import GeneralTree, BST, RBTree
40
+
41
+ # Arbre généraliste
42
+ t = GeneralTree("CEO")
43
+ t.add("CEO", "VP1")
44
+ t.add("CEO", "VP2")
45
+ t.add("VP1", "GM1")
46
+ print(t) # affichage arborescent
47
+ print(t.preorder()) # ['CEO', 'VP1', 'GM1', 'VP2']
48
+
49
+ # ABR non équilibré
50
+ b = BST([50, 30, 70, 20, 40])
51
+ b.insert(60)
52
+ print(b.inorder()) # [20, 30, 40, 50, 60, 70]
53
+ print(b.height, b.is_degenerate)
54
+
55
+ # ARN (rouge-noir), observable
56
+ r = RBTree([50, 30, 70, 20, 40, 60, 80])
57
+ r.validate() # vérifie les 5 invariants
58
+ print(r) # 50(N), 30(R), ...
59
+ print(r.inorder(), r.black_height)
60
+ ```
61
+
62
+ ## API
63
+
64
+ | Structure | Méthodes |
65
+ |---|---|
66
+ | `GeneralTree` | `add`, `prune`, `find`, `preorder`, `postorder`, `levelorder`, `leaves`, `size`, `height` |
67
+ | `BST` | `insert`, `delete`, `find`, `min`, `max`, `successor`, `predecessor`, `inorder`, `preorder`, `postorder`, `levelorder`, `height`, `is_degenerate`, `validate` |
68
+ | `RBTree` | idem `BST` + `root`, `nodes`, `black_height`, `validate`, couleurs `Color.RED/BLACK` |
69
+
70
+ ## Installation
71
+
72
+ ```bash
73
+ pip install arborikit
74
+ ```
75
+
76
+ ## Licence
77
+
78
+ MIT.
@@ -0,0 +1,45 @@
1
+ # arborikit (Python)
2
+
3
+ > Arbres généralistes, ABR non équilibrés et ARN — **zéro dépendance**.
4
+
5
+ ```python
6
+ from arborikit import GeneralTree, BST, RBTree
7
+
8
+ # Arbre généraliste
9
+ t = GeneralTree("CEO")
10
+ t.add("CEO", "VP1")
11
+ t.add("CEO", "VP2")
12
+ t.add("VP1", "GM1")
13
+ print(t) # affichage arborescent
14
+ print(t.preorder()) # ['CEO', 'VP1', 'GM1', 'VP2']
15
+
16
+ # ABR non équilibré
17
+ b = BST([50, 30, 70, 20, 40])
18
+ b.insert(60)
19
+ print(b.inorder()) # [20, 30, 40, 50, 60, 70]
20
+ print(b.height, b.is_degenerate)
21
+
22
+ # ARN (rouge-noir), observable
23
+ r = RBTree([50, 30, 70, 20, 40, 60, 80])
24
+ r.validate() # vérifie les 5 invariants
25
+ print(r) # 50(N), 30(R), ...
26
+ print(r.inorder(), r.black_height)
27
+ ```
28
+
29
+ ## API
30
+
31
+ | Structure | Méthodes |
32
+ |---|---|
33
+ | `GeneralTree` | `add`, `prune`, `find`, `preorder`, `postorder`, `levelorder`, `leaves`, `size`, `height` |
34
+ | `BST` | `insert`, `delete`, `find`, `min`, `max`, `successor`, `predecessor`, `inorder`, `preorder`, `postorder`, `levelorder`, `height`, `is_degenerate`, `validate` |
35
+ | `RBTree` | idem `BST` + `root`, `nodes`, `black_height`, `validate`, couleurs `Color.RED/BLACK` |
36
+
37
+ ## Installation
38
+
39
+ ```bash
40
+ pip install arborikit
41
+ ```
42
+
43
+ ## Licence
44
+
45
+ MIT.
@@ -0,0 +1,49 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "arborikit"
7
+ version = "0.1.0"
8
+ description = "General trees, unbalanced BSTs and red-black trees. Zero dependencies."
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Arborikit contributors" }]
14
+ keywords = ["tree", "bst", "red-black", "arn", "abt", "arbre", "data-structure", "algorithm"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "Intended Audience :: Education",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3 :: Only",
22
+ "Programming Language :: Python :: 3.8",
23
+ "Programming Language :: Python :: 3.9",
24
+ "Programming Language :: Python :: 3.10",
25
+ "Programming Language :: Python :: 3.11",
26
+ "Programming Language :: Python :: 3.12",
27
+ "Programming Language :: Python :: 3.13",
28
+ "Topic :: Education",
29
+ "Topic :: Software Development :: Libraries",
30
+ "Typing :: Typed",
31
+ ]
32
+
33
+ [project.optional-dependencies]
34
+ test = ["pytest>=7"]
35
+
36
+ [project.urls]
37
+ Homepage = "https://github.com/jojo8356/arborikit"
38
+ Repository = "https://github.com/jojo8356/arborikit"
39
+ Issues = "https://github.com/jojo8356/arborikit/issues"
40
+ Changelog = "https://github.com/jojo8356/arborikit/blob/main/CHANGELOG.md"
41
+
42
+ [tool.setuptools]
43
+ package-dir = { "" = "src" }
44
+
45
+ [tool.setuptools.packages.find]
46
+ where = ["src"]
47
+
48
+ [tool.pytest.ini_options]
49
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,26 @@
1
+ """
2
+ arborikit — arbres équilibrés et non équilibrés, sans aucune dépendance.
3
+
4
+ Trois structures, une API cohérente :
5
+ - GeneralTree : arbre généraliste (n-aire), nœuds dynamiques
6
+ - BST : arbre binaire de recherche NON équilibré
7
+ - RBTree : arbre rouge-noir (ARN), équilibré, avec invariants vérifiables
8
+
9
+ Zéro dépendance d'exécution. Python 3.8+.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from .general_tree import GeneralTree, GeneralNode
15
+ from .bst import BST
16
+ from .rbtree import RBTree, Color
17
+
18
+ __version__ = "0.1.0"
19
+ __all__ = [
20
+ "GeneralTree",
21
+ "GeneralNode",
22
+ "BST",
23
+ "RBTree",
24
+ "Color",
25
+ "__version__",
26
+ ]
@@ -0,0 +1,275 @@
1
+ """Arbre binaire de recherche NON équilibré (ABR / BST).
2
+
3
+ Propriété : pour tout nœud, sous-arbre gauche < nœud < sous-arbre droit.
4
+ Complexités : O(log n) en moyenne, O(n) au pire (insertion triée).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any, Iterator, List, Optional
10
+
11
+
12
+ class _Node:
13
+ __slots__ = ("key", "left", "right")
14
+
15
+ def __init__(self, key: Any) -> None:
16
+ self.key = key
17
+ self.left: Optional[_Node] = None
18
+ self.right: Optional[_Node] = None
19
+
20
+ def __repr__(self) -> str:
21
+ return f"_Node({self.key!r})"
22
+
23
+
24
+ class BST:
25
+ """ABR non équilibré, doublons ignorés."""
26
+
27
+ __slots__ = ("_root", "_size")
28
+
29
+ def __init__(self, items: Optional[Any] = None) -> None:
30
+ self._root: Optional[_Node] = None
31
+ self._size = 0
32
+ if items is not None:
33
+ for x in items:
34
+ self.insert(x)
35
+
36
+ # -- état ----------------------------------------------------
37
+ def __len__(self) -> int:
38
+ return self._size
39
+
40
+ def __bool__(self) -> bool:
41
+ return self._root is not None
42
+
43
+ def __contains__(self, key: Any) -> bool:
44
+ return self.find(key) is not None
45
+
46
+ def __iter__(self) -> Iterator[Any]:
47
+ return iter(self.inorder())
48
+
49
+ @property
50
+ def size(self) -> int:
51
+ return self._size
52
+
53
+ @property
54
+ def is_empty(self) -> bool:
55
+ return self._root is None
56
+
57
+ # -- insertion -----------------------------------------------
58
+ def insert(self, key: Any) -> bool:
59
+ """Insère key. Retourne False si déjà présent."""
60
+ if self._root is None:
61
+ self._root = _Node(key)
62
+ self._size = 1
63
+ return True
64
+ cur = self._root
65
+ while True:
66
+ if key == cur.key:
67
+ return False
68
+ if key < cur.key:
69
+ if cur.left is None:
70
+ cur.left = _Node(key)
71
+ self._size += 1
72
+ return True
73
+ cur = cur.left
74
+ else:
75
+ if cur.right is None:
76
+ cur.right = _Node(key)
77
+ self._size += 1
78
+ return True
79
+ cur = cur.right
80
+
81
+ # -- recherche -----------------------------------------------
82
+ def find(self, key: Any) -> Optional[_Node]:
83
+ cur = self._root
84
+ while cur is not None:
85
+ if key == cur.key:
86
+ return cur
87
+ cur = cur.left if key < cur.key else cur.right
88
+ return None
89
+
90
+ def min(self) -> Any:
91
+ if self._root is None:
92
+ raise ValueError("arbre vide")
93
+ cur = self._root
94
+ while cur.left is not None:
95
+ cur = cur.left
96
+ return cur.key
97
+
98
+ def max(self) -> Any:
99
+ if self._root is None:
100
+ raise ValueError("arbre vide")
101
+ cur = self._root
102
+ while cur.right is not None:
103
+ cur = cur.right
104
+ return cur.key
105
+
106
+ def successor(self, key: Any) -> Optional[Any]:
107
+ """Plus petit élément strictement supérieur à key."""
108
+ cur, succ = self._root, None
109
+ while cur is not None:
110
+ if key < cur.key:
111
+ succ, cur = cur.key, cur.left
112
+ elif key > cur.key:
113
+ cur = cur.right
114
+ else:
115
+ if cur.right is not None:
116
+ m = cur.right
117
+ while m.left is not None:
118
+ m = m.left
119
+ return m.key
120
+ return succ
121
+ return succ
122
+
123
+ def predecessor(self, key: Any) -> Optional[Any]:
124
+ cur, pred = self._root, None
125
+ while cur is not None:
126
+ if key > cur.key:
127
+ pred, cur = cur.key, cur.right
128
+ elif key < cur.key:
129
+ cur = cur.left
130
+ else:
131
+ if cur.left is not None:
132
+ m = cur.left
133
+ while m.right is not None:
134
+ m = m.right
135
+ return m.key
136
+ return pred
137
+ return pred
138
+
139
+ # -- suppression ---------------------------------------------
140
+ def delete(self, key: Any) -> bool:
141
+ before = self._size
142
+ self._root = self._delete(self._root, key)
143
+ return self._size < before
144
+
145
+ def _delete(self, node: Optional[_Node], key: Any) -> Optional[_Node]:
146
+ if node is None:
147
+ return None
148
+ if key < node.key:
149
+ node.left = self._delete(node.left, key)
150
+ elif key > node.key:
151
+ node.right = self._delete(node.right, key)
152
+ else:
153
+ self._size -= 1
154
+ if node.left is None:
155
+ return node.right
156
+ if node.right is None:
157
+ return node.left
158
+ nxt = node.right
159
+ while nxt.left is not None:
160
+ nxt = nxt.left
161
+ node.key = nxt.key
162
+ node.right = self._delete(node.right, nxt.key)
163
+ self._size += 1 # annule le décrément du sous-appel
164
+ return node
165
+
166
+ def clear(self) -> None:
167
+ self._root = None
168
+ self._size = 0
169
+
170
+ # -- parcours ------------------------------------------------
171
+ def inorder(self) -> List[Any]:
172
+ """Ordre croissant."""
173
+ out: List[Any] = []
174
+ stack, cur = [], self._root
175
+ while stack or cur is not None:
176
+ while cur is not None:
177
+ stack.append(cur)
178
+ cur = cur.left
179
+ cur = stack.pop()
180
+ out.append(cur.key)
181
+ cur = cur.right
182
+ return out
183
+
184
+ def preorder(self) -> List[Any]:
185
+ out: List[Any] = []
186
+ stack = [self._root] if self._root else []
187
+ while stack:
188
+ n = stack.pop()
189
+ out.append(n.key)
190
+ if n.right is not None:
191
+ stack.append(n.right)
192
+ if n.left is not None:
193
+ stack.append(n.left)
194
+ return out
195
+
196
+ def postorder(self) -> List[Any]:
197
+ out: List[Any] = []
198
+ stack = [self._root] if self._root else []
199
+ while stack:
200
+ n = stack.pop()
201
+ out.append(n.key)
202
+ if n.left is not None:
203
+ stack.append(n.left)
204
+ if n.right is not None:
205
+ stack.append(n.right)
206
+ return out[::-1]
207
+
208
+ def levelorder(self) -> List[Any]:
209
+ out: List[Any] = []
210
+ queue = [self._root] if self._root else []
211
+ i = 0
212
+ while i < len(queue):
213
+ n = queue[i]
214
+ i += 1
215
+ out.append(n.key)
216
+ if n.left is not None:
217
+ queue.append(n.left)
218
+ if n.right is not None:
219
+ queue.append(n.right)
220
+ return out
221
+
222
+ # -- mesures -------------------------------------------------
223
+ @property
224
+ def height(self) -> int:
225
+ """Hauteur : arbre vide = -1, un nœud = 0."""
226
+ if self._root is None:
227
+ return -1
228
+ best, stack = 0, [(self._root, 0)]
229
+ while stack:
230
+ n, d = stack.pop()
231
+ best = max(best, d)
232
+ if n.left is not None:
233
+ stack.append((n.left, d + 1))
234
+ if n.right is not None:
235
+ stack.append((n.right, d + 1))
236
+ return best
237
+
238
+ @property
239
+ def is_degenerate(self) -> bool:
240
+ """Vrai si l'arbre est une liste chaînée (hauteur == size-1)."""
241
+ return self._size > 0 and self.height == self._size - 1
242
+
243
+ # -- vérification --------------------------------------------
244
+ def validate(self) -> None:
245
+ """Lève ValueError si la propriété ABR est violée."""
246
+ stack = [(self._root, None, None)]
247
+ while stack:
248
+ n, lo, hi = stack.pop()
249
+ if n is None:
250
+ continue
251
+ if lo is not None and not (lo < n.key):
252
+ raise ValueError(f"ABR violé : {n.key!r} <= {lo!r}")
253
+ if hi is not None and not (n.key < hi):
254
+ raise ValueError(f"ABR violé : {n.key!r} >= {hi!r}")
255
+ stack.append((n.left, lo, n.key))
256
+ stack.append((n.right, n.key, hi))
257
+
258
+ # -- affichage ------------------------------------------------
259
+ def __str__(self) -> str:
260
+ lines: List[str] = []
261
+
262
+ def rec(n: Optional[_Node], prefix: str, is_last: bool) -> None:
263
+ if n is None:
264
+ return
265
+ lines.append(prefix + ("└── " if is_last else "├── ") + str(n.key))
266
+ child_prefix = prefix + (" " if is_last else "│ ")
267
+ kids = [c for c in (n.left, n.right) if c is not None]
268
+ for i, c in enumerate(kids):
269
+ rec(c, child_prefix, i == len(kids) - 1)
270
+
271
+ rec(self._root, "", True)
272
+ return "\n".join(lines)
273
+
274
+ def __repr__(self) -> str:
275
+ return f"BST(size={self._size}, height={self.height})"
@@ -0,0 +1,184 @@
1
+ """Arbre généraliste (n-aire) : chaque nœud a 0..n enfants et un parent."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Iterator, List, Optional
6
+
7
+
8
+ class GeneralNode:
9
+ """Nœud d'arbre généraliste. `children` est ordonné (insertion)."""
10
+
11
+ __slots__ = ("data", "parent", "children")
12
+
13
+ def __init__(self, data: Any, parent: Optional["GeneralNode"] = None) -> None:
14
+ self.data = data
15
+ self.parent = parent
16
+ self.children: List[GeneralNode] = []
17
+
18
+ def add_child(self, data: Any) -> "GeneralNode":
19
+ child = GeneralNode(data, self)
20
+ self.children.append(child)
21
+ return child
22
+
23
+ def add_node(self, node: "GeneralNode") -> "GeneralNode":
24
+ """Rattache un nœud existant (détaché d'abord de son parent)."""
25
+ if node.parent is not None:
26
+ node.parent.children.remove(node)
27
+ node.parent = self
28
+ self.children.append(node)
29
+ return node
30
+
31
+ def remove_child(self, node: "GeneralNode") -> bool:
32
+ try:
33
+ self.children.remove(node)
34
+ except ValueError:
35
+ return False
36
+ node.parent = None
37
+ return True
38
+
39
+ @property
40
+ def is_leaf(self) -> bool:
41
+ return not self.children
42
+
43
+ @property
44
+ def is_root(self) -> bool:
45
+ return self.parent is None
46
+
47
+ @property
48
+ def depth(self) -> int:
49
+ """Profondeur : racine = 0."""
50
+ d, cur = 0, self
51
+ while cur.parent is not None:
52
+ d += 1
53
+ cur = cur.parent
54
+ return d
55
+
56
+ @property
57
+ def height(self) -> int:
58
+ """Hauteur du sous-arbre : feuille = 0."""
59
+ if not self.children:
60
+ return 0
61
+ return 1 + max(c.height for c in self.children)
62
+
63
+ @property
64
+ def subtree_size(self) -> int:
65
+ return 1 + sum(c.subtree_size for c in self.children)
66
+
67
+ def path_from_root(self) -> List[Any]:
68
+ path, cur = [], self
69
+ while cur is not None:
70
+ path.append(cur.data)
71
+ cur = cur.parent
72
+ return path[::-1]
73
+
74
+ def __iter__(self) -> Iterator["GeneralNode"]:
75
+ return iter(self.children)
76
+
77
+ def __repr__(self) -> str:
78
+ return f"GeneralNode({self.data!r})"
79
+
80
+
81
+ class GeneralTree:
82
+ """Arbre généraliste enveloppant un nœud racine."""
83
+
84
+ def __init__(self, root_data: Any) -> None:
85
+ self.root = GeneralNode(root_data)
86
+
87
+ # -- mesures -------------------------------------------------
88
+ def __len__(self) -> int:
89
+ return self.root.subtree_size
90
+
91
+ def __bool__(self) -> bool:
92
+ return True
93
+
94
+ @property
95
+ def size(self) -> int:
96
+ return len(self)
97
+
98
+ @property
99
+ def height(self) -> int:
100
+ return self.root.height
101
+
102
+ # -- parcours ------------------------------------------------
103
+ def preorder(self) -> List[Any]:
104
+ """Nœud puis enfants."""
105
+ out: List[Any] = []
106
+ stack = [self.root]
107
+ while stack:
108
+ n = stack.pop()
109
+ out.append(n.data)
110
+ stack.extend(reversed(n.children))
111
+ return out
112
+
113
+ def postorder(self) -> List[Any]:
114
+ """Enfants puis nœud."""
115
+ out: List[Any] = []
116
+ root = self.root
117
+
118
+ def rec(n: GeneralNode) -> None:
119
+ for c in n.children:
120
+ rec(c)
121
+ out.append(n.data)
122
+
123
+ rec(root)
124
+ return out
125
+
126
+ def levelorder(self) -> List[Any]:
127
+ """BFS, niveau par niveau."""
128
+ out: List[Any] = []
129
+ queue = [self.root]
130
+ i = 0
131
+ while i < len(queue):
132
+ n = queue[i]
133
+ i += 1
134
+ out.append(n.data)
135
+ queue.extend(n.children)
136
+ return out
137
+
138
+ def leaves(self) -> List[Any]:
139
+ return [n.data for n in self._walk() if n.is_leaf]
140
+
141
+ def _walk(self) -> Iterator[GeneralNode]:
142
+ stack = [self.root]
143
+ while stack:
144
+ n = stack.pop()
145
+ yield n
146
+ stack.extend(reversed(n.children))
147
+
148
+ # -- recherche ----------------------------------------------
149
+ def find(self, data: Any) -> Optional[GeneralNode]:
150
+ for n in self._walk():
151
+ if n.data == data:
152
+ return n
153
+ return None
154
+
155
+ # -- édition -------------------------------------------------
156
+ def add(self, parent_data: Any, data: Any) -> GeneralNode:
157
+ """Raccourci : ajoute `data` sous le nœud contenant `parent_data`."""
158
+ p = self.find(parent_data)
159
+ if p is None:
160
+ raise KeyError(f"nœud parent introuvable : {parent_data!r}")
161
+ return p.add_child(data)
162
+
163
+ def prune(self, data: Any) -> bool:
164
+ """Supprime le nœud et tout son sous-arbre."""
165
+ n = self.find(data)
166
+ if n is None or n.parent is None:
167
+ return False
168
+ return n.parent.remove_child(n)
169
+
170
+ # -- affichage ------------------------------------------------
171
+ def __str__(self) -> str:
172
+ lines: List[str] = []
173
+
174
+ def rec(n: GeneralNode, prefix: str, is_last: bool) -> None:
175
+ lines.append(prefix + ("└── " if is_last else "├── ") + str(n.data))
176
+ child_prefix = prefix + (" " if is_last else "│ ")
177
+ for i, c in enumerate(n.children):
178
+ rec(c, child_prefix, i == len(n.children) - 1)
179
+
180
+ rec(self.root, "", True)
181
+ return "\n".join(lines)
182
+
183
+ def __repr__(self) -> str:
184
+ return f"GeneralTree({self.root.data!r}, size={len(self)})"