TreeNode, ListNode, and GraphNode render as diagrams in Jupyter and clean ASCII in the terminal.
The data structure classes from leetcode_py convert between LeetCode’s
array format and live objects, and render themselves so you can look at
what your code is doing.
from leetcode_py import GraphNode, ListNode, TreeNode
Cyclic lists are safe: traversal detects cycles instead of hanging, in both
directions.Each class carries a few extras beyond conversion and rendering:
TreeNode.find_node(value) returns the first node with that value.
GraphNode.is_clone(other) checks deep equality between a graph and its
copy, the shape clone-graph problems ask for.
All three are generic: TreeNode[int], ListNode[str], and so on.
from leetcode_py.data_structures import DictTree gives a dict-backed
tree that renders with box-drawing characters in the terminal and Graphviz
in Jupyter, which suits Trie implementations.
As the last expression of a cell, these objects render as Graphviz SVG
diagrams. TreeNode lays out top-to-bottom; ListNode goes left-to-right
with rounded boxes. A cyclic list draws the back-edge in red, dashed, and
labeled cycle.
head = ListNode.from_list([1, 2, 3])head.next.next.next = head.next # cycle: 3 -> 2head # renders the diagram, cycle included
print() falls back to clean text: an indented tree, an arrow chain for
lists (cycles shown as ... (cycle back to 2)), and a formatted adjacency
dict for graphs.
Diagram rendering needs the system Graphviz binary (see
Installation). If it is missing, the
objects fall back to the ASCII form, so you get readable output either way.