Add depth for tree

This commit is contained in:
Bertrand Benjamin 2018-01-28 19:13:55 +03:00
parent a916035260
commit 72864f12cd

View File

@ -361,9 +361,6 @@ class Tree(object):
:example: :example:
>>> nested_par = ("+", (
... ("*", (3, 4)),
... 2))
>>> t = Tree.from_str("3*4+2") >>> t = Tree.from_str("3*4+2")
>>> [l for l in t.get_leafs()] >>> [l for l in t.get_leafs()]
[3, 4, 2] [3, 4, 2]
@ -387,17 +384,10 @@ class Tree(object):
:example: :example:
>>> nested_par = ("+", ( >>> t = Tree.from_str('3*4+2')
... ("*", (3, 4)),
... 2))
>>> t = Tree.from_nested_parenthesis(nested_par)
>>> [l for l in t.get_nodes()] >>> [l for l in t.get_nodes()]
['+', '*'] ['+', '*']
>>> nested_par = ("+", ( >>> t = Tree.from_str('3*4+3*4')
... ("*", (3, 4)),
... ("*", (3, 4))
... ))
>>> t = Tree.from_nested_parenthesis(nested_par)
>>> [l for l in t.get_nodes()] >>> [l for l in t.get_nodes()]
['+', '*', '*'] ['+', '*', '*']
""" """
@ -411,6 +401,43 @@ class Tree(object):
except AttributeError: except AttributeError:
pass pass
def depth(self):
""" Return the depth of the tree
:example:
>>> nested_par = ("+", (1, 2))
>>> t = Tree.from_nested_parenthesis(nested_par)
>>> t.depth()
1
>>> nested_par = ("+", (
... ("*", (3, 4)),
... 2))
>>> t = Tree.from_nested_parenthesis(nested_par)
>>> t.depth()
2
>>> nested_par = ("+", (
... ("*", (3,
... ("/", (4, 4))
... )),
... 2))
>>> t = Tree.from_nested_parenthesis(nested_par)
>>> t.depth()
3
"""
try:
l_depth = self.left_value.depth()
except AttributeError:
l_depth = 0
try:
r_depth = self.right_value.depth()
except AttributeError:
r_depth = 0
return 1 + max(l_depth, r_depth)
def __str__(self): def __str__(self):
""" Overload str method """ Overload str method