Skip to content

Instantly share code, notes, and snippets.

@adrientetar
Last active October 22, 2021 12:33
Show Gist options
  • Save adrientetar/e1a3fc8a2182a962b241 to your computer and use it in GitHub Desktop.
Save adrientetar/e1a3fc8a2182a962b241 to your computer and use it in GitHub Desktop.
A simple tree implementation in Python using a list.
"""
A simple btree implementation in Python.
Python 3.3+
"""
class Node:
__slots__ = ['left', 'right', 'value']
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
@property
def children(self):
return (self.left, self.right)
def __repr__(self):
def formatChild(child):
if child is None:
return None
return child.value
return "<{}: {} :: {}, {}>".format(
self.__class__.__name__, self.value,
formatChild(self.left), formatChild(self.right))
"""
Iterate in pre-order depth-first search order (DFS)
"""
def __iter__(self):
yield self
for child in self.children:
if child is not None:
yield from child
else:
yield None
def values(self):
for node in self:
if node is not None:
yield node.value
else:
yield None
"""
3
/ \
1 5
\ /\
2 4 6
"""
rootNode = Node(
3,
Node(1, right=Node(2)),
Node(5, Node(4), Node(6))
)
for node in rootNode:
print(node)
for value in rootNode.values():
print(value)
"""
A simple tree implementation in Python using a list.
Python 3.3+
"""
class Node:
__slots__ = ['_elements']
def __init__(self, val, *children):
self._elements = [val] + list(children)
@property
def children(self):
return self._elements[1:]
@children.setter
def children(self, lst):
self._elements = self._elements[:1] + list(lst)
@children.deleter
def children(self):
self._elements = self._elements[:1]
@property
def value(self):
return self._elements[0]
def __repr__(self):
return "<{}: {} :: {} child nodes>".format(
self.__class__.__name__, self.value, len(self.children))
"""
Iterate in pre-order depth-first search order (DFS)
"""
def __iter__(self):
yield self
for child in self.children:
yield from child
def values(self):
for node in self:
yield node.value
"""
3
/ \
1 5
\ /\
2 4 6
"""
rootNode = Node(
3,
Node(1, Node(2)),
Node(5, Node(4), Node(6))
)
for node in rootNode:
print(node)
for value in rootNode.values():
print(value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment