Build a tree from a list of values and return its root node. :param values: List of node values like those for :func:`binarytree.build`, but with a slightly different representation which associates two adjacent child values with the first parent value that has not been associat
(values: List[NodeValue])
| 2236 | |
| 2237 | |
| 2238 | def build2(values: List[NodeValue]) -> Optional[Node]: |
| 2239 | """Build a tree from a list of values and return its root node. |
| 2240 | |
| 2241 | :param values: List of node values like those for :func:`binarytree.build`, but |
| 2242 | with a slightly different representation which associates two adjacent child |
| 2243 | values with the first parent value that has not been associated yet. This |
| 2244 | representation does not provide the same indexing properties where if a node |
| 2245 | is at index i, its left child is always at 2i + 1, right child at 2i + 2, and |
| 2246 | parent at floor((i - 1) / 2), but it allows for more compact lists as it |
| 2247 | does not hold "None"s between nodes in each level. See example below for an |
| 2248 | illustration. |
| 2249 | :type values: [float | int | str | None] |
| 2250 | :return: Root node of the binary tree. |
| 2251 | :rtype: binarytree.Node | None |
| 2252 | :raise binarytree.exceptions.NodeNotFoundError: If the list representation |
| 2253 | is malformed (e.g. a parent node is missing). |
| 2254 | |
| 2255 | **Example**: |
| 2256 | |
| 2257 | .. doctest:: |
| 2258 | |
| 2259 | >>> from binarytree import build2 |
| 2260 | >>> |
| 2261 | >>> root = build2([2, 5, None, 3, None, 1, 4]) |
| 2262 | >>> |
| 2263 | >>> print(root) |
| 2264 | <BLANKLINE> |
| 2265 | 2 |
| 2266 | / |
| 2267 | __5 |
| 2268 | / |
| 2269 | 3 |
| 2270 | / \\ |
| 2271 | 1 4 |
| 2272 | <BLANKLINE> |
| 2273 | |
| 2274 | .. doctest:: |
| 2275 | |
| 2276 | >>> from binarytree import build2 |
| 2277 | >>> |
| 2278 | >>> root = build2([None, 1, 2]) # doctest: +IGNORE_EXCEPTION_DETAIL |
| 2279 | Traceback (most recent call last): |
| 2280 | ... |
| 2281 | binarytree.exceptions.NodeValueError: node value must be a float/int/str |
| 2282 | """ |
| 2283 | queue: Deque[Node] = deque() |
| 2284 | root: Optional[Node] = None |
| 2285 | |
| 2286 | if values: |
| 2287 | root = Node(values[0]) |
| 2288 | queue.append(root) |
| 2289 | |
| 2290 | index = 1 |
| 2291 | while index < len(values): |
| 2292 | node = queue.popleft() |
| 2293 | |
| 2294 | if values[index] is not None: |
| 2295 | node.left = Node(values[index]) |