Skip to content

Instantly share code, notes, and snippets.

@ZechCodes
Created May 21, 2023 13:35
Show Gist options
  • Save ZechCodes/72bf4c6757745ded99c46419e7ac1e12 to your computer and use it in GitHub Desktop.
Save ZechCodes/72bf4c6757745ded99c46419e7ac1e12 to your computer and use it in GitHub Desktop.
A simple unordered tree implementation in Python for the weekly coding prompt on the Beginner.Codes Discord server. Join now https://beginner.codes/discord
from typing import Generic, TypeVar
T = TypeVar("T")
class Node(Generic[T]):
def __init__(self, value: T, parent: "Node[T] | None" = None):
self._children = tuple()
self._parent = parent
self._value = value
@property
def children(self) -> "tuple[Node[T]]":
return self._children
@property
def is_root(self):
return self._parent is None
@property
def parent(self) -> "Node[T]":
return self._parent or self
@property
def value(self) -> T:
return self._value
def add_child(self, child: "Node[T]"):
self._children = (*self.children, child)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment