Balancing a AssocialTree

This commit is contained in:
Bertrand Benjamin 2018-01-31 17:18:52 +03:00
parent 935a0d0d23
commit a0fa09a381

View File

@ -966,6 +966,102 @@ class AssocialTree(Tree):
except AttributeError: except AttributeError:
yield callback(self.right_value) yield callback(self.right_value)
def balance(self):
""" Balance the tree
:example:
>>> t = AssocialTree.from_str("1+2+3+4+5+6+7+8+9")
>>> print(t)
+
> +
| > +
| | > +
| | | > +
| | | | > +
| | | | | > +
| | | | | | > +
| | | | | | | > 1
| | | | | | | > 2
| | | | | | > 3
| | | | | > 4
| | | | > 5
| | | > 6
| | > 7
| > 8
> 9
>>> bal_t = t.balance()
>>> print(bal_t)
+
> +
| > +
| | > 1
| | > 2
| > +
| | > 3
| | > 4
> +
| > +
| | > 5
| | > 6
| > +
| | > 7
| | > +
| | | > 8
| | | > 9
>>> t = AssocialTree.from_str("1*2*3*4*5+6+7+8+9")
>>> print(t)
+
> +
| > +
| | > +
| | | > *
| | | | > *
| | | | | > *
| | | | | | > *
| | | | | | | > 1
| | | | | | | > 2
| | | | | | > 3
| | | | | > 4
| | | | > 5
| | | > 6
| | > 7
| > 8
> 9
>>> bal_t = t.balance()
>>> print(bal_t)
+
> +
| > *
| | > *
| | | > 1
| | | > 2
| | > *
| | | > 3
| | | > *
| | | | > 4
| | | | > 5
| > 6
> +
| > 7
| > +
| | > 8
| | > 9
:returns: Balanced Tree (not AssocialTree)
"""
leafs = self.get_leafs()
balanced_leafs = []
for l in leafs:
try:
balanced_leafs.append(l.balance())
except AttributeError:
balanced_leafs.append(l)
t = Tree.from_list(self.node, balanced_leafs)
return t
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4: