generated from nullndr/pyproj
add basic tree
This commit is contained in:
10
src/main.py
10
src/main.py
@@ -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
31
src/tree.py
Normal 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))
|
||||||
Reference in New Issue
Block a user