add basic tree
Some checks failed
Run tests / test (push) Failing after 1m40s
Code Quality / lint (push) Failing after 1m44s

This commit is contained in:
2026-01-25 23:40:26 +01:00
parent b7fd8f8c6c
commit 02f60b1d7e
2 changed files with 40 additions and 1 deletions

View File

@@ -1,10 +1,18 @@
#! /usr/bin/env python #! /usr/bin/env python
from strings import * from strings import *
from tree import *
def main(): def main():
string_ex() t = build_tree((1, (2, (3, None, None), None), (4, None, None)))
print(t)
assert t.val == 1
assert t.left.val == 2
assert t.left.left.val == 3
assert t.right.val == 4
pass pass

31
src/tree.py Normal file
View File

@@ -0,0 +1,31 @@
class Tree:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __repr__(self):
return f"({self.val} {self.__print_leaf(self.left)} {self.__print_leaf(self.right)})"
def __print_leaf(self, leaf):
if leaf:
return f"{leaf}"
return "<empty>"
def build_tree(args: Tuple):
if args == None:
return None
if not isinstance(args, tuple):
raise "Invalid argument"
if len(args) != 3:
raise "Invalid number of parameters in the tuple"
value, right, left = args
if (not isinstance(right, tuple) and right != None) or (not isinstance(left, tuple) and left != None):
raise "Nodes must be tuples"
return Tree(value, build_tree(right), build_tree(left))