Skip to content

Commit

Permalink
fixed trees
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidLeoni committed Dec 9, 2018
1 parent 883a29d commit 4073e9c
Show file tree
Hide file tree
Showing 4 changed files with 316 additions and 92 deletions.
43 changes: 38 additions & 5 deletions exercises/trees/bin_tree_solution.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,41 @@ def left(self):
def right(self):
return self._right


def __str__(self):
""" Returns a pretty string of the tree """
def str_branches(node, branches):
""" Returns a string with the tree pretty printed.
branches: a list of characters representing the parent branches. Characters can be either ` ` or '│'
"""
strings = [str(node._data)]

i = 0
if node._left != None or node._right != None:
for current in [node._left, node._right]:
if i == 0:
joint = '├'
else:
joint = '└'

strings.append('\n')
for b in branches:
strings.append(b)
strings.append(joint)
if i == 0:
branches.append('│')
else:
branches.append(' ')

if current != None:
strings.append(str_branches(current, branches))
branches.pop()
i += 1
return "".join(strings)

return str_branches(self, [])


def insert_left(self, data):
""" Takes as input DATA (*NOT* a node !!) and MODIFIES current node this way:
Expand Down Expand Up @@ -74,20 +108,19 @@ def height_rec(self):

def depth_dfs(self, level):
"""
- MODIFIES the tree by putting in the data field the value level + 1,
- MODIFIES the tree by putting in the data field the provided value level (which is an integer),
and recursively calls itself on left and right nodes (if present) passing level + 1
- implement it as a recursive Depth First Search (DFS) traversal
NOTE: with big trees a recursive solution would surely exceed the call stack,
but here we don't mind
- The root of a tree has depth zero.
- does not return anything
"""
#jupman-raise
self._data = level + 1
self._data = level
if self.left() != None:
self.left().depth_dfs(level + 1)
if self.right() != None:
self.right().depth_dfs(level + 1)
#/jupman-raise


13 changes: 7 additions & 6 deletions exercises/trees/bin_tree_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,11 @@ def bt(*args):
children = args[1:]

ret = BinaryTree(data)

cs = list(reversed(children))
if len(cs) > 0:
ret._left = cs[0]
if len(cs) == 2:
ret._right = cs[1]

if len(children) > 0:
ret._left = children[0]
if len(children) == 2:
ret._right = children[1]
return ret


Expand Down Expand Up @@ -222,3 +221,5 @@ def test_insert_right(self):
self.assertEqual(tb.right(), tc)
self.assertEqual(tc.left(), None)
self.assertEqual(tc.right(), None)


0 comments on commit 4073e9c

Please sign in to comment.