Ticket #14498: trac_14498-tree-imps-dg.patch

File trac_14498-tree-imps-dg.patch, 59.7 KB (added by darij, 6 years ago)

improvements and bugfixes

  • sage/combinat/abstract_tree.py

    # HG changeset patch
    # User darij grinberg <darijgrinberg@gmail.com>
    # Date 1381115904 25200
    # Node ID 7143d785ec5b6a7a705ecc969af391caff125ead
    # Parent  03c64cb58c0b2cc418abbc90982fb12ba10373d1
    trac #14498: some improvements on trees
    
    diff --git a/sage/combinat/abstract_tree.py b/sage/combinat/abstract_tree.py
    a b incoherent with the data structure. 
    6666from sage.structure.list_clone import ClonableArray
    6767from sage.rings.integer import Integer
    6868from sage.misc.misc_c import prod
    69 from sage.misc import lazy_attribute
    7069###############################################################################
    7170# # use to load tikz in the preamble (one for *view* and one for *notebook*)
    7271from sage.misc.latex import latex
    class AbstractTree(object): 
    860859
    861860    def tree_factorial(self):
    862861        """
    863         Returns the tree-factorial of ``self``
     862        Return the tree-factorial of ``self``
    864863
    865864        Definition:
    866865
  • sage/combinat/binary_tree.py

    diff --git a/sage/combinat/binary_tree.py b/sage/combinat/binary_tree.py
    a b  
    22"""
    33Binary Trees
    44
    5 This module deals with binary trees as mathematical (in particular immmutable)
     5This module deals with binary trees as mathematical (in particular immutable)
    66objects.
    77
    88.. NOTE::
    AUTHORS: 
    1717REFERENCES:
    1818
    1919.. [LodayRonco] Jean-Louis Loday and María O. Ronco.
    20    *Hopf algebra of the planar binary trees*.
    21    
     20   *Hopf algebra of the planar binary trees*,
     21   Advances in Mathematics, volume 139, issue 2,
     22   10 November 1998, pp. 293-309.
     23   http://www.sciencedirect.com/science/article/pii/S0001870898917595
     24
    2225.. [HNT05] Florent Hivert, Jean-Christophe Novelli, and Jean-Yves Thibon.
    23    *The algebra of binary search trees*.
     26   *The algebra of binary search trees*,
     27   :arxiv:`math/0401089v2`.
     28
     29.. [CP12] Gregory Chatel, Vivane Pons.
     30   *Counting smaller trees in the Tamari order*,
     31   :arxiv:`1212.0751v1`.
    2432"""
    2533#*****************************************************************************
    2634#       Copyright (C) 2010 Florent Hivert <Florent.Hivert@univ-rouen.fr>,
    class BinaryTree(AbstractClonableTree, C 
    4351    """
    4452    Binary trees.
    4553
    46     Binary trees here mean ordered (a.k.a. plane) binary trees,
    47     meaning that the children of each node are ordered.
     54    Binary trees here mean ordered (a.k.a. plane) finite binary
     55    trees, where "ordered" means that the children of each node are
     56    ordered.
     57
     58    Binary trees contain nodes and leaves, where each node has two
     59    children while each leaf has no children. The number of leaves
     60    always equals the number of nodes plus `1`.
    4861
    4962    INPUT:
    5063
    5164    - ``children`` -- ``None`` (default) or a list, tuple or iterable of
    52       length 2 of binary trees or convertible objects. This corresponds to
    53       the standard recursive definition of a binary tree as either a leaf
    54       or a pair of binary trees. Syntactic sugar allows leaving out all
    55       but the outermost calls of the ``BinaryTree()`` constructor, so that,
    56       e. g., ``BinaryTree([BinaryTree(None),BinaryTree(None)])`` can be
    57       simplified to ``BinaryTree([None,None])``. It is also allowed to
     65      length `2` of binary trees or convertible objects. This corresponds
     66      to the standard recursive definition of a binary tree as either a
     67      leaf or a pair of binary trees. Syntactic sugar allows leaving out
     68      all but the outermost calls of the ``BinaryTree()`` constructor, so
     69      that, e. g., ``BinaryTree([BinaryTree(None),BinaryTree(None)])`` can
     70      be simplified to ``BinaryTree([None,None])``. It is also allowed to
    5871      abbreviate ``[None, None]`` by ``[]``.
    5972
    6073    - ``check`` -- (default to ``True``) whether check for binary should be
    class BinaryTree(AbstractClonableTree, C 
    97110    def __classcall_private__(cls, *args, **opts):
    98111        """
    99112        Ensure that binary trees created by the enumerated sets and directly
    100         are the same and that they are instances of :class:`BinaryTree`
     113        are the same and that they are instances of :class:`BinaryTree`.
    101114
    102115        TESTS::
    103116
    class BinaryTree(AbstractClonableTree, C 
    127140    @lazy_class_attribute
    128141    def _auto_parent(cls):
    129142        """
    130         The automatic parent of the element of this class
     143        The automatic parent of the elements of this class.
    131144
    132145        When calling the constructor of an element of this class, one needs a
    133146        parent. This class attribute specifies which parent is used.
    class BinaryTree(AbstractClonableTree, C 
    138151            Binary trees
    139152            sage: BinaryTree([None, None]).parent()
    140153            Binary trees
    141          """
     154        """
    142155        return BinaryTrees_all()
    143156
    144157    def __init__(self, parent, children = None, check = True):
    class BinaryTree(AbstractClonableTree, C 
    174187
    175188    def check(self):
    176189        """
    177         Checks that ``self`` is a binary tree
     190        Check that ``self`` is a binary tree.
    178191
    179192        EXAMPLES::
    180193
    class BinaryTree(AbstractClonableTree, C 
    410423
    411424    def is_empty(self):
    412425        """
    413         Return whether ``self`` is  empty.
     426        Return whether ``self`` is empty.
     427
     428        The notion of emptiness employed here is the one which defines
     429        a binary tree to be empty if its root is a leaf. There is
     430        precisely one empty binary tree.
    414431
    415432        EXAMPLES::
    416433
    class BinaryTree(AbstractClonableTree, C 
    423440        """
    424441        return not self
    425442
    426     def graph(self):
     443    def graph(self, with_leaves=True):
    427444        """
    428         Convert ``self`` to a digraph
    429 
    430         EXAMPLE::
     445        Convert ``self`` to a digraph. By default, this graph contains
     446        both nodes and leaves, hence is never empty. To obtain a graph
     447        which contains only the nodes, the ``with_leaves`` optional
     448        keyword variable has to be set to ``False``.
     449
     450        INPUT:
     451
     452        - ``with_leaves`` -- (default: ``True``) a Boolean, determining
     453          whether the resulting graph will be formed from the leaves
     454          and the nodes of ``self`` (if ``True``), or only from the
     455          nodes of ``self`` (if ``False``)
     456
     457        EXAMPLES::
    431458
    432459            sage: t1 = BinaryTree([[], None])
    433460            sage: t1.graph()
    434461            Digraph on 5 vertices
     462            sage: t1.graph(with_leaves=False)
     463            Digraph on 2 vertices
    435464
    436465            sage: t1 = BinaryTree([[], [[], None]])
    437466            sage: t1.graph()
    438467            Digraph on 9 vertices
    439468            sage: t1.graph().edges()
    440469            [(0, 1, None), (0, 4, None), (1, 2, None), (1, 3, None), (4, 5, None), (4, 8, None), (5, 6, None), (5, 7, None)]
     470            sage: t1.graph(with_leaves=False)
     471            Digraph on 4 vertices
     472            sage: t1.graph(with_leaves=False).edges()
     473            [(0, 1, None), (0, 2, None), (2, 3, None)]
     474
     475            sage: t1 = BinaryTree()
     476            sage: t1.graph()
     477            Digraph on 1 vertex
     478            sage: t1.graph(with_leaves=False)
     479            Digraph on 0 vertices
     480
     481            sage: BinaryTree([]).graph()
     482            Digraph on 3 vertices
     483            sage: BinaryTree([]).graph(with_leaves=False)
     484            Digraph on 1 vertex
     485
     486            sage: t1 = BinaryTree([[], [[], []]])
     487            sage: t1.graph(with_leaves=False)
     488            Digraph on 5 vertices
     489            sage: t1.graph(with_leaves=False).edges()
     490            [(0, 1, None), (0, 2, None), (2, 3, None), (2, 4, None)]
    441491        """
    442492        from sage.graphs.graph import DiGraph
    443         res = DiGraph()
    444         def rec(tr, idx):
    445             if not tr:
    446                 return
    447             else:
    448                 nbl = 2*tr[0].node_number() + 1
    449                 res.add_edges([[idx,idx+1], [idx,idx+1+nbl]])
    450                 rec(tr[0], idx + 1)
    451                 rec(tr[1], idx + nbl + 1)
    452         rec(self, 0)
    453         return res
     493
     494        if with_leaves:   # We want leaves and nodes.
     495
     496            # Special treatment for the case when self has only 1 vertex.
     497            # In this case, rec(self, 0) would give a false result.
     498            if not self:
     499                return DiGraph([[0], lambda i,j: False])
     500   
     501            res = DiGraph()
     502            # The edge set of res will be built up step by step using the
     503            # following function:
     504            def rec(tr, idx):
     505                if not tr:  # tr is a leaf.
     506                    return
     507                else:  # tr is a node.
     508                    nbl = 2*tr[0].node_number() + 1
     509                    res.add_edges([[idx,idx+1], [idx,idx+1+nbl]])
     510                    rec(tr[0], idx + 1)
     511                    rec(tr[1], idx + nbl + 1)
     512            rec(self, 0)
     513            return res
     514
     515        else:   # We want only the nodes.
     516
     517            # Special treatment for the case when self has only 1 node.
     518            # In this case, the general DiGraph construction would
     519            # falsely yield an empty graph (since it adds nodes only
     520            # implicitly by adding edges).
     521            if self.node_number() == 1:
     522                return DiGraph([[0], lambda i,j: False])
     523
     524            res = DiGraph()
     525            # The edge set of res will be built up step by step using the
     526            # following function:
     527            def rec(tr, idx):
     528                if not tr:  # tr is a leaf.
     529                    return
     530                else:  # tr is a node.
     531                    nbl = tr[0].node_number()
     532                    if nbl > 0:
     533                        res.add_edge([idx, idx + 1])
     534                        rec(tr[0], idx + 1)
     535                    if tr[1].node_number() > 0:
     536                        res.add_edge([idx, idx + nbl + 1])
     537                        rec(tr[1], idx + nbl + 1)
     538            rec(self, 0)
     539            return res
    454540
    455541    def canonical_labelling(self,shift=1):
    456542        """
    457543        Return a labelled version of ``self``.
    458544
     545        The canonical labelling of a binary tree is a certain labelling of the
     546        nodes (not the leaves) of the tree.
    459547        The actual canonical labelling is currently unspecified. However, it
    460548        is guaranteed to have labels in `1...n` where `n` is the number of
    461549        nodes of the tree. Moreover, two (unlabelled) trees compare as equal if
    class BinaryTree(AbstractClonableTree, C 
    479567        else:
    480568            return LTR(None)
    481569
    482     def show(self):
     570    def show(self, with_leaves=False):
    483571        """
     572        Show the binary tree ``show``, with or without leaves depending
     573        on the Boolean keyword variable ``with_leaves``.
     574
     575        .. WARNING::
     576
     577            Left and right children might get interchanged in
     578            the actual picture.
     579
    484580        TESTS::
    485581
    486582            sage: t1 = BinaryTree([[], [[], None]])
    487583            sage: t1.show()
    488584        """
    489         self.graph().show(layout='tree', tree_root=0, tree_orientation="down")
     585        try:
     586            self.graph(with_leaves=with_leaves).show(layout='tree', tree_root=0, tree_orientation="down")
     587        except RuntimeError:
     588            # This is for the border case BinaryTree().show().
     589            self.graph(with_leaves=with_leaves).show()
    490590
    491591    def make_node(self, child_list = [None, None]):
    492592        """
    493         Modify ``self`` so that it becomes a node with children ``childlist``
     593        Modify ``self`` so that it becomes a node with children ``child_list``.
    494594
    495595        INPUT:
    496596
    class BinaryTree(AbstractClonableTree, C 
    509609            ...
    510610            ValueError: object is immutable; please change a copy instead.
    511611            sage: with t.clone() as t1:
    512             ...    t1.make_node([None, None])
     612            ....:     t1.make_node([None, None])
    513613            sage: t, t1
    514614            (., [., .])
    515615            sage: with t.clone() as t:
    516             ...    t.make_node([BinaryTree(), BinaryTree(), BinaryTree([])])
     616            ....:     t.make_node([BinaryTree(), BinaryTree(), BinaryTree([])])
    517617            Traceback (most recent call last):
    518618            ...
    519619            ValueError: the list must have length 2
    520620            sage: with t1.clone() as t2:
    521             ...    t2.make_node([t1, t1])
     621            ....:     t2.make_node([t1, t1])
    522622            sage: with t2.clone() as t3:
    523             ...    t3.make_node([t1, t2])
     623            ....:     t3.make_node([t1, t2])
    524624            sage: t1, t2, t3
    525625            ([., .], [[., .], [., .]], [[., .], [[., .], [., .]]])
    526626        """
    class BinaryTree(AbstractClonableTree, C 
    532632
    533633    def make_leaf(self):
    534634        """
    535         Modify ``self`` so that it became a leaf
     635        Modify ``self`` so that it becomes a leaf (i. e., an empty tree).
    536636
    537637        .. NOTE:: ``self`` must be in a mutable state.
    538638
    class BinaryTree(AbstractClonableTree, C 
    547647            ...
    548648            ValueError: object is immutable; please change a copy instead.
    549649            sage: with t.clone() as t1:
    550             ...    t1.make_leaf()
     650            ....:     t1.make_leaf()
    551651            sage: t, t1
    552652            ([., .], .)
    553653        """
    class BinaryTree(AbstractClonableTree, C 
    584684    def to_dyck_word_tamari(self):
    585685        r"""
    586686        Return the Dyck word associated with ``self`` in consistency with
    587         the Tamari order on dyck words and binary trees.
     687        the Tamari order on Dyck words and binary trees.
    588688
    589689        The bijection is defined recursively as follows:
    590690
    class BinaryTree(AbstractClonableTree, C 
    604704            sage: BinaryTree([[[], [[], None]], [[], []]]).to_dyck_word_tamari()
    605705            [1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0]
    606706        """
    607         from sage.combinat.dyck_word import DyckWord
    608707        return self.to_dyck_word("L1R0")
    609708
    610709    @combinatorial_map(name="to Dyck paths: up step, left tree, down step, right tree")
    611710    def to_dyck_word(self, usemap="1L0R"):
    612711        r"""
     712        Return the Dyck word associated with ``self`` using the given map.
     713
    613714        INPUT:
    614715
    615716        - ``usemap`` -- a string, either ``1L0R``, ``1R0L``, ``L1R0``, ``R1L0``
    616717
    617         Return the Dyck word associated with ``self`` using the given map.
    618 
    619718        The bijection is defined recursively as follows:
    620719
    621720        - a leaf is associated to the empty Dyck Word
    622721
    623722        - a tree with children `l,r` is associated with the Dyck word
    624723          described by ``usemap`` where `L` and `R` are respectively the
    625           Dyck words associated with the `l` and `r`.
     724          Dyck words associated with the trees `l` and `r`.
    626725
    627726        EXAMPLES::
    628727
    class BinaryTree(AbstractClonableTree, C 
    727826    @combinatorial_map(name="To ordered tree, right child = right brother")
    728827    def to_ordered_tree_right_branch(self):
    729828        r"""
    730         Return an ordered tree of size n+1 by the following recursive rule:
     829        Return an ordered tree of size `n+1` by the following recursive rule:
    731830
    732831        - if `x` is the right child of `y`, `x` becomes the right brother
    733832          of `y`
    class BinaryTree(AbstractClonableTree, C 
    783882        Return a 312-avoiding permutation corresponding to the binary tree.
    784883
    785884        The linear extensions of a binary tree form an interval of the weak
    786         order called the sylester class of the tree. This permutation is
     885        order called the sylvester class of the tree. This permutation is
    787886        the minimal element of this sylvester class.
    788887
    789888        EXAMPLES::
    class BinaryTree(AbstractClonableTree, C 
    808907        return Permutation(self._postfix_word())
    809908
    810909    @combinatorial_map(name="To complete tree")
    811     def as_ordered_tree(self,with_leaves=True):
     910    def as_ordered_tree(self, with_leaves=True):
    812911        r"""
    813912        Return the same tree seen as an ordered tree. By default, leaves
    814         are transformed into actual nodes.
     913        are transformed into actual nodes, but this can be avoided by
     914        setting the optional variable ``with_leaves`` to ``False``.
    815915
    816916        EXAMPLES::
    817917
    class BinaryTree(AbstractClonableTree, C 
    831931        if with_leaves:
    832932            children = [child.as_ordered_tree(with_leaves) for child in self]
    833933        else:
     934            if not self:
     935                raise ValueError("The empty binary tree cannot be made into an ordered tree with with_leaves = False")
    834936            children = [child.as_ordered_tree(with_leaves) for child in self if not child.is_empty()]
    835937        if self in LabelledBinaryTrees():
    836938            from sage.combinat.ordered_tree import LabelledOrderedTree
    class BinaryTree(AbstractClonableTree, C 
    840942            return OrderedTree(children)
    841943
    842944    @combinatorial_map(name="To graph")
    843     def to_undirected_graph(self, with_leaves = False):
     945    def to_undirected_graph(self, with_leaves=False):
    844946        r"""
    845947        Return the undirected graph obtained from the tree nodes and edges.
    846         Leafs are ignored by default but can set ``with_leaves`` to ``True``
    847         to obtain the graph of the complete tree.
     948        Leaves are ignored by default, but one can set ``with_leaves`` to
     949        ``True`` to obtain the graph of the complete tree.
     950
     951        INPUT:
     952
     953        - ``with_leaves`` -- (default: ``False``) a Boolean, determining
     954          whether the resulting graph will be formed from the leaves
     955          and the nodes of ``self`` (if ``True``), or only from the
     956          nodes of ``self`` (if ``False``)
    848957
    849958        EXAMPLES::
    850959
    class BinaryTree(AbstractClonableTree, C 
    854963            sage: bt.to_undirected_graph(with_leaves=True)
    855964            Graph on 3 vertices
    856965
     966            sage: bt = BinaryTree()
     967            sage: bt.to_undirected_graph()
     968            Graph on 0 vertices
     969            sage: bt.to_undirected_graph(with_leaves=True)
     970            Graph on 1 vertex
     971
    857972        If the tree is labelled, we use its labelling to label the graph.
    858973        Otherwise, we use the graph canonical labelling which means that
    859974        two different trees can have the same graph.
    class BinaryTree(AbstractClonableTree, C 
    872987            sage: BinaryTree([[],[]]).to_undirected_graph() == BinaryTree([[[],None],None]).to_undirected_graph()
    873988            True
    874989        """
     990        if (not with_leaves) and (not self):
     991            # this case needs extra care :(
     992            from sage.graphs.graph import Graph
     993            return Graph([])
    875994        return self.as_ordered_tree(with_leaves).to_undirected_graph()
    876995
    877996    @combinatorial_map(name="To poset")
    878     def to_poset(self, with_leaves = False, root_to_leaf=False):
     997    def to_poset(self, with_leaves=False, root_to_leaf=False):
    879998        r"""
    880         Return the poset obtained by interpreting the tree as a hasse
     999        Return the poset obtained by interpreting the tree as a Hasse
    8811000        diagram.
    8821001
    8831002        The default orientation is from leaves to root but you can
    8841003        pass ``root_to_leaf=True`` to obtain the inverse orientation.
    8851004
    886         Leafs are ignored by default but can set ``with_leaves`` to ``True``
    887         to obtain the poset of the complete tree.
     1005        Leaves are ignored by default, but one can set ``with_leaves`` to
     1006        ``True`` to obtain the poset of the complete tree.
    8881007
    8891008        INPUT:
    8901009
    891         - ``with_leaves`` -- boolean, true if leaves should be added to the poset
    892         - ``root_to_leaf`` -- boolean, true if the poset orientation should
    893           be from root to leaves. It is false by default.
     1010        - ``with_leaves`` -- (default: ``False``) a Boolean, determining
     1011          whether the resulting poset will be formed from the leaves
     1012          and the nodes of ``self`` (if ``True``), or only from the
     1013          nodes of ``self`` (if ``False``)
     1014        - ``root_to_leaf`` -- (default: ``False``) a Boolean,
     1015          determining whether the poset orientation should be from root
     1016          to leaves (if ``True``) or from leaves to root (if ``False``).
    8941017
    8951018        EXAMPLES::
    8961019
    class BinaryTree(AbstractClonableTree, C 
    9131036            2[1[., .], 3[., 4[., .]]]
    9141037            sage: bt.to_poset().cover_relations()
    9151038            [[4, 3], [3, 2], [1, 2]]
     1039
     1040        Let us check that the empty binary tree is correctly handled::
     1041
     1042            sage: bt = BinaryTree()
     1043            sage: bt.to_poset()
     1044            Finite poset containing 0 elements
     1045            sage: bt.to_poset(with_leaves=True)
     1046            Finite poset containing 1 elements
    9161047        """
     1048        if (not with_leaves) and (not self):
     1049            # this case needs extra care :(
     1050            from sage.combinat.posets.posets import Poset
     1051            return Poset({})
    9171052        return self.as_ordered_tree(with_leaves).to_poset(root_to_leaf)
    9181053
    9191054    @combinatorial_map(name="To 132 avoiding permutation")
    class BinaryTree(AbstractClonableTree, C 
    9221057        Return a 132-avoiding permutation corresponding to the binary tree.
    9231058
    9241059        The linear extensions of a binary tree form an interval of the weak
    925         order called the sylester class of the tree. This permutation is
     1060        order called the sylvester class of the tree. This permutation is
    9261061        the maximal element of this sylvester class.
    9271062
    9281063        EXAMPLES::
    class BinaryTree(AbstractClonableTree, C 
    10131148
    10141149    def canopee(self):
    10151150        """
    1016         Return the canopee of ``self``
    1017 
    1018         The *canopee* of a non empty binary tree `T` with `n` internal nodes is
     1151        Return the canopee of ``self``.
     1152
     1153        The *canopee* of a non-empty binary tree `T` with `n` internal nodes is
    10191154        the list `l` of `0` and `1` of length `n-1` obtained by going along the
    10201155        leaves of `T` from left to right except the two extremal ones, writing
    10211156        `0` if the leaf is a right leaf and `1` if the leaf is a left leaf.
    class BinaryTree(AbstractClonableTree, C 
    10351170
    10361171        The number of pairs `(t_1, t_2)` of binary trees of size `n` such that
    10371172        the canopee of `t_1` is the complementary of the canopee of `t_2` is
    1038         also the number of Baxter permutations (see [DG]_, see
     1173        also the number of Baxter permutations (see [DG94]_, see
    10391174        also :oeis:`A001181`). We check this in small cases::
    10401175
    10411176            sage: [len([(u,v) for u in BinaryTrees(n) for v in BinaryTrees(n)
    1042             ...       if map(lambda x:1-x, u.canopee()) == v.canopee()])
    1043             ...    for n in range(1, 5)]
     1177            ....:       if map(lambda x:1-x, u.canopee()) == v.canopee()])
     1178            ....:    for n in range(1, 5)]
    10441179            [1, 2, 6, 22]
    10451180
    10461181        Here is a less trivial implementation of this::
    class BinaryTree(AbstractClonableTree, C 
    10481183            sage: from sage.sets.finite_set_map_cy import fibers
    10491184            sage: from sage.misc.all import attrcall
    10501185            sage: def baxter(n):
    1051             ...      f = fibers(lambda t: tuple(t.canopee()),
    1052             ...                   BinaryTrees(n))
    1053             ...      return sum(len(f[i])*len(f[tuple(1-x for x in i)])
    1054             ...                 for i in f)
     1186            ....:     f = fibers(lambda t: tuple(t.canopee()),
     1187            ....:                   BinaryTrees(n))
     1188            ....:     return sum(len(f[i])*len(f[tuple(1-x for x in i)])
     1189            ....:                for i in f)
    10551190            sage: [baxter(n) for n in range(1, 7)]
    10561191            [1, 2, 6, 22, 92, 422]
    10571192
    class BinaryTree(AbstractClonableTree, C 
    10641199
    10651200        REFERENCES:
    10661201
    1067             .. [DG] S. Dulucq and O, Guibert. Mots de piles, tableaux
    1068                standards et permutations de Baxter, proceedings of
    1069                Formal Power Series and Algebraic Combinatorics, 1994.
     1202        .. [DG94] S. Dulucq and O. Guibert. Mots de piles, tableaux
     1203           standards et permutations de Baxter, proceedings of
     1204           Formal Power Series and Algebraic Combinatorics, 1994.
    10701205        """
    10711206        if not self:
    10721207            raise ValueError("canopee is only defined for non empty binary trees")
    class BinaryTree(AbstractClonableTree, C 
    10821217
    10831218    def in_order_traversal_iter(self):
    10841219        """
    1085         The depth-first infix-order traversal iterator.
    1086 
    1087         This method iters each node following the infix order traversal
    1088         algorithm.
    1089 
    1090         For example on the following binary tree `T` where we denote leaves by
    1091         `a, b, c, \ldots` and nodes by `1, 2, 3, \ldots`::
     1220        The depth-first infix-order traversal iterator for the binary
     1221        tree ``self``.
     1222
     1223        This method iters each vertex (node and leaf alike) following the
     1224        depth-first infix order traversal algorithm.
     1225
     1226        The *depth-first infix order traversal algorithm* iterates
     1227        through a binary tree as follows::
     1228
     1229            iterate through the left subtree (by the depth-first infix
     1230                order traversal algorithm);
     1231            yield the root;
     1232            iterate through the right subtree (by the depth-first infix
     1233                order traversal algorithm).
     1234
     1235        For example on the following binary tree `T`, where we denote
     1236        leaves by `a, b, c, \ldots` and nodes by `1, 2, 3, \ldots`::
    10921237
    10931238            |     ____3____          |
    10941239            |    /         \         |
    class BinaryTree(AbstractClonableTree, C 
    11001245            |         / \   / \      |
    11011246            |        d   e f   g     |
    11021247
    1103         the *depth-first infixe-order traversal algorithm* explores `T` in
    1104         the following order of nodes `a,1,b,2,c,3,d,4,e,5,f,6,g,7,h,8,i`.
    1105 
    1106         ALGORITHM::
    1107 
    1108             explore the left subtree
    1109             manipulate the root with function `node_action` if the root is
    1110                 a node and with function `leaf_action` if it is a leaf
    1111             explore the right subtree
     1248        the depth-first infix-order traversal algorithm iterates through
     1249        the vertices of `T` in the following order:
     1250        `a,1,b,2,c,3,d,4,e,5,f,6,g,7,h,8,i`.
     1251
     1252        See :meth:`in_order_traversal` for a version of this algorithm
     1253        which not only iterates through, but actually does something at
     1254        the vertices of tree.
    11121255
    11131256        TESTS::
    11141257
    class BinaryTree(AbstractClonableTree, C 
    11491292
    11501293    def in_order_traversal(self, node_action=None, leaf_action=None):
    11511294        r"""
    1152         The depth-first infix-order traversal algorithm.
    1153 
    1154         .. SEEALSO::
    1155 
    1156             :meth:`~sage.combinat.binary_tree.BinaryTree.in_order_traversal_iter()`
     1295        Explore the binary tree ``self`` using the depth-first infix-order
     1296        traversal algorithm, executing the ``node_action`` function
     1297        whenever traversing a node and executing the ``leaf_action``
     1298        function whenever traversing a leaf.
     1299
     1300        In more detail, what this method does to a tree `T` is the
     1301        following::
     1302
     1303            if the root of `T` is a node:
     1304                apply in_order_traversal to the left subtree of `T`
     1305                    (with the same node_action and leaf_action);
     1306                apply node_action to the root of `T`;
     1307                apply in_order_traversal to the right subtree of `T`
     1308                    (with the same node_action and leaf_action);
     1309            else:
     1310                apply leaf_action to the root of `T`.
     1311
     1312        For example on the following binary tree `T`, where we denote
     1313        leaves by `a, b, c, \ldots` and nodes by `1, 2, 3, \ldots`::
     1314
     1315            |     ____3____          |
     1316            |    /         \         |
     1317            |   1          __7__     |
     1318            |  / \        /     \    |
     1319            | a   2      _5_     8   |
     1320            |    / \    /   \   / \  |
     1321            |   b   c  4     6 h   i |
     1322            |         / \   / \      |
     1323            |        d   e f   g     |
     1324
     1325        this method first applies ``leaf_action`` to `a`, then applies
     1326        ``node_action`` to `1`, then ``leaf_action`` to `b`, then
     1327        ``node_action`` to `2`, etc., with the vertices being traversed
     1328        in the order `a,1,b,2,c,3,d,4,e,5,f,6,g,7,h,8,i`.
     1329
     1330        See :meth:`in_order_traversal_iter` for a version of this
     1331        algorithm which only iterates through the vertices rather than
     1332        applying any function to them.
    11571333
    11581334        INPUT:
    11591335
    class BinaryTree(AbstractClonableTree, C 
    12171393
    12181394    def tamari_greater(self):
    12191395        r"""
    1220         The list of all trees greater than ``self``.
     1396        The list of all trees greater or equal to ``self`` in the Tamari
     1397        order.
    12211398        This is the transitive ideal of its successors.
    12221399
    1223         The tree::
     1400        The Tamari order on binary trees of size `n` is the partial order
     1401        on the set of all binary trees of size `n` generated by the
     1402        following requirement:  If a binary tree `T'` is obtained by
     1403        right rotation (see :meth:`right_rotate`) from a binary tree `T`,
     1404        then `T < T'`.
     1405        This not only is a well-defined partial order, but actually is
     1406        a lattice structure on the set of binary trees of size `n`, and
     1407        is a quotient of the weak order on the `n`-th symmetric group.
     1408        See [CP12]_.
     1409
     1410        For example, the tree::
    12241411
    12251412            |     __o__   |
    12261413            |    /     \  |
    class BinaryTree(AbstractClonableTree, C 
    12281415            |  / \     /  |
    12291416            | o   o   o   |
    12301417
    1231         has these trees greater than it::
     1418        has these trees greater or equal to it::
    12321419
    12331420            |o          , o        , o        , o        ,  o       ,   o      ,|
    12341421            | \            \          \          \           \           \      |
    class BinaryTree(AbstractClonableTree, C 
    12751462
    12761463    def tamari_pred(self):
    12771464        r"""
    1278         Compute the list of predecessor of ``self`` in the tamari poset.
     1465        Compute the list of predecessors of ``self`` in the Tamari poset.
    12791466        This list is computed by all left rotate possible on
    12801467        its nodes.
    12811468
    class BinaryTree(AbstractClonableTree, C 
    13211508
    13221509    def tamari_smaller(self):
    13231510        r"""
    1324         The list of all trees smaller than ``self``.
     1511        The list of all trees smaller or equal to ``self`` in the Tamari
     1512        order.
    13251513        This is the transitive ideal of its predecessors.
    13261514
    13271515        The tree::
    class BinaryTree(AbstractClonableTree, C 
    13321520            |  / \     /  |
    13331521            | o   o   o   |
    13341522
    1335         has these trees smaller than it::
     1523        has these trees smaller or equal to it::
    13361524
    13371525            |    __o__  ,       _o_  ,        o ,         o,         o,           o |
    13381526            |   /     \        /   \         /           /          /            /  |
    class BinaryTree(AbstractClonableTree, C 
    13631551
    13641552    def tamari_succ(self):
    13651553        r"""
    1366         Compute the list of successors of ``self`` in the tamari poset.
    1367         There is the list of all trees obtains by a right rotate of
     1554        Compute the list of successors of ``self`` in the Tamari poset.
     1555        There is the list of all trees obtained by a right rotate of
    13681556        one of its nodes.
    13691557
    1370         The list of successor of::
     1558        The list of successors of::
    13711559
    13721560            |     __o__   |
    13731561            |    /     \  |
    class BinaryTree(AbstractClonableTree, C 
    13921580            [[[[., .], .], .], .]
    13931581            sage: b.tamari_succ()
    13941582            [[[[., .], .], [., .]], [[[., .], [., .]], .], [[[., [., .]], .], .]]
     1583
     1584            sage: b = B([])
     1585            sage: b.tamari_succ()
     1586            []
     1587
     1588            sage: b = B([[],[]])
     1589            sage: b.tamari_succ()
     1590            [[., [., [., .]]]]
    13951591        """
    13961592        res = []
    13971593        if self.is_empty():
    class BinaryTree(AbstractClonableTree, C 
    14031599             [B([g, self[1]]) for g in self[0].tamari_succ()] +
    14041600             [B([self[0], d]) for d in self[1].tamari_succ()])
    14051601
    1406     def q_hook_length_formula(self):
     1602    def q_hook_length_fraction(self, q=None, q_factor=False):
    14071603        r"""
    1408         Compute the ``q-hook length formula`` of a binary tree.
    1409 
    1410         If `q=1` then ``q-hook length formula`` computes the number of
    1411         permutations such that the shape of binary search tree associated is
    1412         *self*.
     1604        Compute the ``q``-hook length fraction of the binary tree ``self``,
     1605        with an additional "q-factor" if desired.
     1606
     1607        If `T` is a (plane) binary tree and `q` is a polynomial
     1608        indeterminate over some ring, then the `q`-hook length fraction
     1609        `h_{q} (T)` of `T` is defined by
    14131610
    14141611        .. MATH::
    14151612
    1416             f_{q} (T) = \frac{[\lvert T \rvert]_q!}{\prod_{t \in T}
    1417             q^{right(t)} \lvert t \rvert]_q}
    1418 
    1419         where `\lvert T \rvert` is the node number of `T`, `t \in T` the set
    1420         of all subtrees of `T`, and `right(t)` the number of nodes of the
    1421         right subtree of `t`.
    1422 
    1423         There are `20` permutations which give a binary tree of the
     1613            h_{q} (T)
     1614            = \frac{[\lvert T \rvert]_q!}{\prod_{t \in T}
     1615            [\lvert T_t \rvert]_q},
     1616
     1617        where the product ranges over all nodes `t` of `T`, where `T_t`
     1618        denotes the subtree of `T` consisting of `t` and its all
     1619        descendants, and where for every tree `S`, we denote by
     1620        `\lvert S \rvert` the number of nodes of `S`. While this
     1621        definition only shows that `h_{q} (T)` is a rational function
     1622        in `T`, it is in fact easy to show that `h_{q} (T)` is
     1623        actually a polynomial in `T`, and thus makes sense when any
     1624        element of a commutative ring is substituted for `q`.
     1625        This can also be explicitly seen from the following recursive
     1626        formula for `h_{q} (T)`:
     1627
     1628        .. MATH::
     1629
     1630            h_{q} (T)
     1631            = \binom{ \lvert T \rvert - 1 }{ \lvert T_1 \rvert }_q
     1632            h_{q} (T_1) h_{q} (T_2),
     1633
     1634        where `T` is any nonempty binary tree, and `T_1` and `T_2` are
     1635        the two children trees of the root of `T`, and where
     1636        `\binom{a}{b}_q` denotes a `q`-binomial coefficient.
     1637
     1638        A variation of the `q`-hook length fraction is the following
     1639        "`q`-hook length fraction with `q`-factor"::
     1640
     1641        .. MATH::
     1642
     1643            f_{q} (T)
     1644            = h_{q} (T) \cdot
     1645            \prod_{t \in T} q^{\lvert T_{\mathrm{right}(t)} \rvert},
     1646
     1647        where for every node `t`, we denote by `\mathrm{right}(t)` the
     1648        right child of `t`.
     1649        This `f_{q} (T)` differs from `h_{q} (T)` only in a
     1650        multiplicative factor, which is a power of `q`.
     1651
     1652        When `q = 1`, both `f_{q} (T)` and `h_{q} (T)` equal the number
     1653        of permutations whose binary search tree (see [HNT05]_ for the
     1654        definition) is `T` (after dropping the labels). For example,
     1655        there are `20` permutations which give a binary tree of the
    14241656        following shape::
    14251657
    14261658            |     __o__   |
    class BinaryTree(AbstractClonableTree, C 
    14291661            |  / \     /  |
    14301662            | o   o   o   |
    14311663
    1432         by the binary search insertion algorithm.
    1433 
    1434         TESTS::
     1664        by the binary search insertion algorithm, in accordance with
     1665        the fact that this tree satisfies `f_{1} (T) = 20`.
     1666
     1667        When `q` is considered as a polynomial indeterminate,
     1668        `f_{q} (T)` is the generating function for all permutations
     1669        whose binary search tree is `T` (after dropping the labels)
     1670        with respect to the number of inversions (i. e., the Coxeter
     1671        length) of the permutations.
     1672
     1673        Objects similar to `h_{q} (T)` also make sense for general
     1674        ordered forests (rather than just binary trees), see e. g.
     1675        [BW88]_, Theorem 9.1.
     1676
     1677        INPUT:
     1678
     1679        - ``q`` -- a ring element which is to be substituted as `q`
     1680          into the `q`-hook length fraction (by default, this is
     1681          set to be the indeterminate `q` in the polynomial ring
     1682          `\ZZ[q]`)
     1683
     1684        - ``q_factor`` -- a Boolean (default: ``False``) which
     1685          determines whether to compute `h_{q} (T)` or to
     1686          compute `f_{q} (T)` (namely, `h_{q} (T)` is obtained when
     1687          ``q_factor == False``, and `f_{q} (T)` is obtained when
     1688          ``q_factor == True``)
     1689
     1690        REFERENCES:
     1691
     1692        .. [BW88] Anders Bjoerner, Michelle L. Wachs,
     1693           *Generalized quotients in Coxeter groups*.
     1694           Transactions of the American Mathematical Society,
     1695           vol. 308, no. 1, July 1988.
     1696           http://www.ams.org/journals/tran/1988-308-01/S0002-9947-1988-0946427-X/S0002-9947-1988-0946427-X.pdf
     1697       
     1698        EXAMPLES:
     1699
     1700        Let us start with a simple example. Actually, let us start
     1701        with the easiest possible example -- the binary tree with
     1702        only one vertex (which is a leaf):
     1703
     1704            sage: b = BinaryTree()
     1705            sage: b.q_hook_length_fraction()
     1706            1
     1707            sage: b.q_hook_length_fraction(q_factor=True)
     1708            1
     1709
     1710        Nothing different for a tree with one node and two leaves::
     1711
     1712            sage: b = BinaryTree([]); b
     1713            [., .]
     1714            sage: b.q_hook_length_fraction()
     1715            1
     1716            sage: b.q_hook_length_fraction(q_factor=True)
     1717            1
     1718
     1719        Let us get to a more interesting tree::
    14351720
    14361721            sage: b = BinaryTree([[[],[]],[[],None]]); b
    14371722            [[[., .], [., .]], [[., .], .]]
    1438             sage: b.q_hook_length_formula()(q=1)
     1723            sage: b.q_hook_length_fraction()(q=1)
    14391724            20
    1440             sage: BinaryTree([[],[]]).q_hook_length_formula()
    1441             (((q + 2)*q + 2)*q + 1)*q/((q + 1)*q + 1)
     1725            sage: b.q_hook_length_fraction()
     1726            q^7 + 2*q^6 + 3*q^5 + 4*q^4 + 4*q^3 + 3*q^2 + 2*q + 1
     1727            sage: b.q_hook_length_fraction(q_factor=True)
     1728            q^10 + 2*q^9 + 3*q^8 + 4*q^7 + 4*q^6 + 3*q^5 + 2*q^4 + q^3
     1729            sage: b.q_hook_length_fraction(q=2)
     1730            465
     1731            sage: b.q_hook_length_fraction(q=2, q_factor=True)
     1732            3720
     1733            sage: q = PolynomialRing(ZZ, 'q').gen()
     1734            sage: b.q_hook_length_fraction(q=q**2)
     1735            q^14 + 2*q^12 + 3*q^10 + 4*q^8 + 4*q^6 + 3*q^4 + 2*q^2 + 1
     1736
     1737        Let us check the fact that `f_{q} (T)` is the generating function
     1738        for all permutations whose binary search tree is `T` (after
     1739        dropping the labels) with respect to the number of inversions of
     1740        the permutations::
     1741
     1742            sage: def q_hook_length_fraction_2(T):
     1743            ....:     P = PolynomialRing(ZZ, 'q')
     1744            ....:     q = P.gen()
     1745            ....:     res = P.zero()
     1746            ....:     for w in T.sylvester_class():
     1747            ....:         res += q ** Permutation(w).length()
     1748            ....:     return res
     1749            sage: def test_genfun(i):
     1750            ....:     return all( q_hook_length_fraction_2(T)
     1751            ....:                 == T.q_hook_length_fraction(q_factor=True)
     1752            ....:                 for T in BinaryTrees(i) )
     1753            sage: test_genfun(4)
     1754            True
     1755            sage: test_genfun(7)  # long time
     1756            True
    14421757        """
    1443         from sage.combinat.q_analogues import q_factorial, q_int
    1444         from sage.symbolic.ring import SymbolicRing
    1445 
    1446         q = SymbolicRing().var('q')
    1447 
    1448         def product_of_subtrees(b):
    1449             if b.is_empty():
    1450                 return q ** 0
    1451             return (q ** (-b[0].node_number()) * q_int(b.node_number())) * \
    1452                 product_of_subtrees(b[0]) * product_of_subtrees(b[1])
    1453 
    1454         return q_factorial(self.node_number()) / product_of_subtrees(self)
     1758        from sage.combinat.q_analogues import q_binomial
     1759
     1760        if q is None:
     1761            from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
     1762            from sage.rings.integer_ring import ZZ
     1763            basering = PolynomialRing(ZZ, 'q')
     1764            q = basering.gen()
     1765        else:
     1766            basering = q.base_ring()
     1767
     1768        if q_factor:
     1769            def product_of_subtrees(b):
     1770                if b.is_empty():
     1771                    return basering.one()
     1772                b0 = b[0]
     1773                b1 = b[1]
     1774                return q_binomial(b.node_number() - 1, b0.node_number(), q=q) * \
     1775                    product_of_subtrees(b0) * product_of_subtrees(b1) * \
     1776                    q ** (b1.node_number())
     1777        else:
     1778            def product_of_subtrees(b):
     1779                if b.is_empty():
     1780                    return basering.one()
     1781                b0 = b[0]
     1782                b1 = b[1]
     1783                return q_binomial(b.node_number() - 1, b0.node_number(), q=q) * \
     1784                    product_of_subtrees(b0) * product_of_subtrees(b1)
     1785
     1786        return product_of_subtrees(self)
    14551787
    14561788    @combinatorial_map(name="Right rotate")
    14571789    def right_rotate(self):
    14581790        r"""
    1459         Right rotation operation of tree.
    1460 
    1461         The right rotation is defined by::
     1791        Return the result of right rotation applied to the binary
     1792        tree ``self``.
     1793
     1794        Right rotation on binary trees is defined as follows:
     1795        Let `T` be a nonempty binary tree such that the left
     1796        child of the root of `T` is a node. Let `C` be the right
     1797        child of the root of `T`, and let `A` and `B` be the
     1798        left and right children of the left child of the root
     1799        of `T`. (Keep in mind that nodes of trees are identified
     1800        with the subtrees consisting of their descendants.)
     1801        Then, the right rotation of `T` is the nonempty binary
     1802        tree in which the left child of the root is `A`, whereas
     1803        the right child of the root is a node whose left and right
     1804        children are `B` and `C`. In pictures::
     1805
     1806            |     *                      *     |
     1807            |    / \                    / \    |
     1808            |   *   C -right-rotate->  A   *   |
     1809            |  / \                        / \  |
     1810            | A   B                      B   C |
     1811
     1812        where asterisks signify a single node each (but `A`, `B`
     1813        and `C` might be empty).
     1814
     1815        For example,
    14621816
    14631817            |     o                     _o_   |
    14641818            |    /                     /   \  |
    class BinaryTree(AbstractClonableTree, C 
    14741828            |  /     \                               \      |
    14751829            | o       o                               o     |
    14761830
     1831        Right rotation is the inverse operation to left rotation
     1832        (:meth:`left_rotate`).
     1833
     1834        The right rotation operation introduced here is the one defined
     1835        in Definition 2.1 of [CP12]_.
     1836
     1837        .. SEEALSO::
     1838
     1839            :meth:`left_rotate`
     1840
    14771841        EXAMPLES::
    14781842
    14791843            sage: b = BinaryTree([[[],[]], None]); ascii_art([b])
    class BinaryTree(AbstractClonableTree, C 
    14881852            [ o     o ]
    14891853            [      /  ]
    14901854            [     o   ]
    1491             sage: b = BinaryTree([[[[],None],[None,[]]], []]);ascii_art([b])
     1855            sage: b = BinaryTree([[[[],None],[None,[]]], []]); ascii_art([b])
    14921856            [       __o__   ]
    14931857            [      /     \  ]
    14941858            [     o       o ]
    class BinaryTree(AbstractClonableTree, C 
    15111875    @combinatorial_map(name="Left rotate")
    15121876    def left_rotate(self):
    15131877        r"""
    1514         Left rotation operation of tree.
    1515 
    1516         The left rotation is defined by::
     1878        Return the result of left rotation applied to the binary
     1879        tree ``self``.
     1880
     1881        Left rotation on binary trees is defined as follows:
     1882        Let `T` be a nonempty binary tree such that the right
     1883        child of the root of `T` is a node. Let `A` be the left
     1884        child of the root of `T`, and let `B` and `C` be the
     1885        left and right children of the right child of the root
     1886        of `T`. (Keep in mind that nodes of trees are identified
     1887        with the subtrees consisting of their descendants.)
     1888        Then, the left rotation of `T` is the nonempty binary
     1889        tree in which the right child of the root is `C`, whereas
     1890        the left child of the root is a node whose left and right
     1891        children are `A` and `B`. In pictures::
     1892
     1893            |   *                        *   |
     1894            |  / \                      / \  |
     1895            | A   *  -left-rotate->    *   C |
     1896            |    / \                  / \    |
     1897            |   B   C                A   B   |
     1898
     1899        where asterisks signify a single node each (but `A`, `B`
     1900        and `C` might be empty).
     1901
     1902        For example,
    15171903
    15181904            |   _o_                        o |
    15191905            |  /   \                      /  |
    class BinaryTree(AbstractClonableTree, C 
    15311917            |                                 /     \  |
    15321918            |                                o       o |
    15331919
     1920        Left rotation is the inverse operation to right rotation
     1921        (:meth:`right_rotate`).
     1922
     1923        .. SEEALSO::
     1924
     1925            :meth:`right_rotate`
     1926
    15341927        EXAMPLES::
    15351928
    15361929            sage: b = BinaryTree([[],[[],None]]); ascii_art([b])
    class BinaryTree(AbstractClonableTree, C 
    15541947    @combinatorial_map(name="Over operation on Binary Trees")
    15551948    def over(self, bt):
    15561949        r"""
    1557         The ``over`` (`/`) operation defined by Loday-Ronco [LodayRonco]_.
     1950        Return ``self`` over ``bt``, where "over" is the ``over`` (`/`)
     1951        operation defined by Loday-Ronco [LodayRonco]_.
     1952
     1953        If `T` and `T'` are two binary trees, then `T` over `T'`
     1954        (written `T / T'`) is defined as the tree obtained by grafting
     1955        `T'` on the rightmost node of `T`. See section 4.5 of [HNT05]_.
     1956
     1957        TODO::
     1958
     1959            Fix this doc and figure out which of the different
     1960            (inconsistent?) notations to follow. I don't see the
     1961            "over" operation defined in [LodayRonco]_, although
     1962            [HNT05]_ pretends that it is defined there. In
     1963            [HNT05]_ the definition is somewhat vague about the
     1964            order of the operads. Loday and Ronco seem to define
     1965            "over" on page 2 of "Order structure on the algebra
     1966            of permutations and of planar binary trees", but
     1967            with a different choice of left/right.
    15581968
    15591969        This is defined by::
    15601970
    class BinaryTree(AbstractClonableTree, C 
    16782088
    16792089    def sylvester_class(self, left_to_right=False):
    16802090        r"""
    1681         Iterate the sylvester class corresponding to the binary tree.
    1682        
    1683         The sylvester class is the set of permutations corresponding to the
    1684         canonical binary search tree with same shape of ``self``.
    1685         See [HNT05]_ for more.
    1686        
    1687         For example the following has the permutations `(1,3,2)` and `(3,1,2)`
    1688         associated::
     2091        Iterate over the sylvester class corresponding to the binary tree
     2092        ``self``.
     2093
     2094        The sylvester class of a tree `T` is the set of permutations
     2095        `\sigma` whose binary search tree (a notion defined in [HNT05]_,
     2096        Definition 7) is `T` after forgetting the labels. This is an
     2097        equivalence class of the sylvester congruence (the congruence on
     2098        words which sets two words `uacvbw` and `ucavbw` congruent
     2099        whenever `a`, `b`, `c` are letters satisfying `a \leq b < c`, and
     2100        extends by transitivity) on the symmetric group.
     2101
     2102        For example the following tree's sylvester class consists of the
     2103        permutations `(1,3,2)` and `(3,1,2)`::
    16892104
    16902105            [   o   ]
    16912106            [  / \  ]
    16922107            [ o   o ]
    1693        
     2108
     2109        (only the nodes are drawn here).
     2110
     2111        The binary search tree of a word is constructed by an RSK-like
     2112        algorithm, in which the word is read from right to left. If a
     2113        left-to-right reading is to be employed instead, the
     2114        ``left_to_right`` optional keyword variable should be set to
     2115        ``True``.
     2116
    16942117        TESTS::
    1695        
     2118
    16962119            sage: list(BinaryTree([[],[]]).sylvester_class())
    16972120            [[1, 3, 2], [3, 1, 2]]
    16982121            sage: bt = BinaryTree([[[],None],[[],[]]])
    class BinaryTree(AbstractClonableTree, C 
    17172140             [6, 4, 1, 2, 5, 3],
    17182141             [6, 4, 1, 5, 2, 3],
    17192142             [6, 4, 5, 1, 2, 3]]
    1720             sage: len(l) == Integer(bt.q_hook_length_formula()(q=1))
     2143            sage: len(l) == Integer(bt.q_hook_length_fraction()(q=1))
    17212144            True
     2145
     2146        Border cases::
     2147
     2148            sage: list(BinaryTree().sylvester_class())
     2149            [[]]
     2150            sage: list(BinaryTree([]).sylvester_class())
     2151            [[1]]
    17222152        """
    17232153        if self.is_empty():
    17242154            yield []
    class BinaryTree(AbstractClonableTree, C 
    17422172
    17432173    def is_full(self):
    17442174        r"""
    1745         A full binary tree is a tree in which every node other than the leaves
    1746         has two children.
     2175        Return ``True`` if ``self`` is full, else return ``False``.
     2176
     2177        A full binary tree is a tree in which every node either has two
     2178        child nodes or has two child leaves.
    17472179
    17482180        This is also known as *proper binary tree* or *2-tree* or *strictly
    17492181        binary tree*.
    class BinaryTree(AbstractClonableTree, C 
    17892221
    17902222    def is_perfect(self):
    17912223        r"""
     2224        Return ``True`` if ``self`` is perfect, else return ``False``.
     2225
    17922226        A perfect binary tree is a full tree in which all leaves are at the
    17932227        same depth.
    17942228
    class BinaryTree(AbstractClonableTree, C 
    18352269
    18362270    def is_complete(self):
    18372271        r"""
     2272        Return ``True`` if ``self`` is complete, else return ``False``.
     2273
    18382274        A complete binary tree is a perfect binary tree except possibly in the
    18392275        last level.
    18402276
    class BinaryTree(AbstractClonableTree, C 
    18532289            |  / \     / \      |
    18542290            | o   o   o   o     |
    18552291
    1856         is not complet but the following ones are::
     2292        is not complete but the following ones are::
    18572293
    18582294            |     __o__          _o_            ___o___     |
    18592295            |    /     \        /   \          /       \    |
    class BinaryTree(AbstractClonableTree, C 
    18652301
    18662302        EXAMPLES::
    18672303
    1868 
    18692304            sage: lst = lambda i: filter(lambda bt: bt.is_complete(), BinaryTrees(i))
    18702305            sage: for i in range(9): ascii_art(lst(i)) # long time
    18712306            [  ]
    class BinaryTrees(UniqueRepresentation,  
    19812416            return BinaryTrees_all()
    19822417        else:
    19832418            if not (isinstance(n, (Integer, int)) and n >= 0):
    1984                 raise ValueError("n must be a non negative integer")
     2419                raise ValueError("n must be a nonnegative integer")
    19852420            return BinaryTrees_size(Integer(n))
    19862421
    19872422    @cached_method
    class BinaryTrees_size(BinaryTrees): 
    22502685
    22512686class LabelledBinaryTree(AbstractLabelledClonableTree, BinaryTree):
    22522687    """
    2253     The class of labelled binary tree
     2688    Labelled binary trees.
     2689
     2690    A labelled binary tree is a binary tree (see :class:`BinaryTree` for
     2691    the meaning of this) with a label assigned to each node. (The labels
     2692    need not be integers, nor are they required to be distinct. ``None``
     2693    can be used as a label.)
     2694
     2695    .. TODO::
     2696
     2697        Explain how to init these.
     2698
     2699        Maybe allow ``LabelledBinaryTree()`` syntax for
     2700        ``LabelledBinaryTree(None)`` (in analogy to ``BinaryTree``
     2701        class).
    22542702
    22552703    EXAMPLE::
    22562704
    class LabelledBinaryTree(AbstractLabelle 
    22812729    @lazy_class_attribute
    22822730    def _auto_parent(cls):
    22832731        """
    2284         The automatic parent of the element of this class
     2732        The automatic parent of the elements of this class.
    22852733
    22862734        When calling the constructor of an element of this class, one needs a
    22872735        parent. This class attribute specifies which parent is used.
    class LabelledBinaryTree(AbstractLabelle 
    23152763
    23162764    def binary_search_insert(self, letter):
    23172765        """
    2318         Insert a letter in a binary search tree
     2766        Return the result of inserting a letter ``letter`` into the
     2767        right strict binary search tree ``self``.
    23192768
    23202769        INPUT:
    23212770
    23222771        - ``letter`` -- any object comparable with the label of ``self``
    23232772
     2773        OUTPUT:
     2774
     2775        The right strict binary search tree ``self`` with ``letter``
     2776        inserted into it according to the binary search insertion
     2777        algorithm.
     2778
    23242779        .. NOTE:: ``self`` is supposed to be a binary search tree. No check is
    23252780                  performed.
    23262781
     2782        A right strict binary search tree is defined to be a labelled
     2783        binary tree such that for each node `n` with label `x`,
     2784        every descendant of the left child of `n` has a label `\leq x`,
     2785        and every descendant of the right child of `n` has a label
     2786        `> x`. (Here, only nodes count as descendants, and every node
     2787        counts as its own descendant too.)
     2788
     2789        .. TODO::
     2790
     2791            Explain the algorithm.
     2792
    23272793        EXAMPLES::
    23282794
    23292795            sage: LBT = LabelledBinaryTree
    class LabelledBinaryTree(AbstractLabelle 
    23352801            3[1[., .], .]
    23362802            sage: res = LBT(None)
    23372803            sage: for i in [3,1,5,2,4,6]:
    2338             ...       res = res.binary_search_insert(i)
     2804            ....:     res = res.binary_search_insert(i)
    23392805            sage: res
    23402806            3[1[., 2[., .]], 5[4[., .], 6[., .]]]
    23412807        """
    class LabelledBinaryTree(AbstractLabelle 
    23522818
    23532819    def right_rotate(self):
    23542820        r"""
    2355         Right rotation operation of a tree.
    2356 
    2357         The right rotation of a tree is defined by::
     2821        Return the result of right rotation applied to the labelled
     2822        binary tree ``self``.
     2823
     2824        Right rotation on labelled binary trees is defined as
     2825        follows: Let `T` be a nonempty labelled binary tree such
     2826        that the left child of the root of `T` is a node. Let
     2827        `C` be the right child of the root of `T`, and let `A`
     2828        and `B` be the left and right children of the left child
     2829        of the root of `T`. (Keep in mind that nodes of trees are
     2830        identified with the subtrees consisting of their
     2831        descendants.) Furthermore, let `y` be the label at the
     2832        root of `T`, and `x` be the label at the left child of the
     2833        root of `T`.
     2834        Then, the right rotation of `T` is the nonempty labelled
     2835        binary tree in which the root is labelled `x`, the left
     2836        child of the root is `A`, whereas the right child of the
     2837        root is a node labelled `y` whose left and right children
     2838        are `B` and `C`. In pictures::
    23582839
    23592840            |     y                      x     |
    23602841            |    / \                    / \    |
    class LabelledBinaryTree(AbstractLabelle 
    23622843            |  / \                        / \  |
    23632844            | A   B                      B   C |
    23642845
     2846        Right rotation is the inverse operation to left rotation
     2847        (:meth:`left_rotate`).
     2848
    23652849        TESTS::
    23662850
    23672851            sage: LB = LabelledBinaryTree
    class LabelledBinaryTree(AbstractLabelle 
    23782862
    23792863    def left_rotate(self):
    23802864        r"""
    2381         Left rotation operation of a tree.
    2382 
    2383         The left rotation of a tree is defined by::
     2865        Return the result of left rotation applied to the labelled
     2866        binary tree ``self``.
     2867
     2868        Left rotation on labelled binary trees is defined as
     2869        follows: Let `T` be a nonempty labelled binary tree such
     2870        that the right child of the root of `T` is a node. Let
     2871        `A` be the left child of the root of `T`, and let `B`
     2872        and `C` be the left and right children of the right child
     2873        of the root of `T`. (Keep in mind that nodes of trees are
     2874        identified with the subtrees consisting of their
     2875        descendants.) Furthermore, let `x` be the label at the
     2876        root of `T`, and `y` be the label at the right child of the
     2877        root of `T`.
     2878        Then, the left rotation of `T` is the nonempty labelled
     2879        binary tree in which the root is labelled `y`, the right
     2880        child of the root is `C`, whereas the left child of the
     2881        root is a node labelled `x` whose left and right children
     2882        are `A` and `B`. In pictures::
    23842883
    23852884           |     y                    x     |
    23862885           |    / \                  / \    |
    class LabelledBinaryTree(AbstractLabelle 
    23882887           |  / \                      / \  |
    23892888           | A   B                    B   C |
    23902889
     2890        Left rotation is the inverse operation to right rotation
     2891        (:meth:`right_rotate`).
     2892
    23912893        TESTS::
    23922894
    23932895            sage: LB = LabelledBinaryTree
    class LabelledBinaryTree(AbstractLabelle 
    24042906
    24052907    def heap_insert(self, l):
    24062908        r"""
    2407         Insert a letter in a binary heap (tree).
    2408 
    2409         Roughly, a binary heap will be a complete binary tree such that for
    2410         each nodes the label is greater or equals to the label of its children.
     2909        Return the result of inserting a letter ``l`` into the binary
     2910        heap (tree) ``self``.
     2911
     2912        Roughly, a binary heap will be a labelled complete binary tree
     2913        such that for each node the label is greater or equal to the
     2914        label of each of its children.
    24112915
    24122916        For example::
    24132917
    class LabelledBinaryTree(AbstractLabelle 
    24172921            |  / \      |
    24182922            | 3   4     |
    24192923
     2924        is a binary heap.
     2925
    24202926        INPUT:
    24212927
    24222928        - ``letter`` -- any object comparable with the label of ``self``
  • sage/combinat/ordered_tree.py

    diff --git a/sage/combinat/ordered_tree.py b/sage/combinat/ordered_tree.py
    a b from sage.combinat.combinatorial_map imp 
    2626
    2727class OrderedTree(AbstractClonableTree, ClonableList):
    2828    """
    29     The class for (ordered rooted) Trees
     29    The class of (ordered rooted) trees.
    3030
    31     An ordered tree is constructed from a node called the root on which one
     31    An ordered tree is constructed from a node, called the root, on which one
    3232    has grafted a possibly empty list of trees. There is a total order on the
    3333    children of a node which is given by the order of the elements in the
    34     list. Note that there is no empty ordered tree.
     34    list. Note that there is no empty ordered tree (so the smallest ordered
     35    tree consists of just one node).
    3536
    3637    INPUT:
    3738
    class OrderedTree(AbstractClonableTree,  
    6263        sage: tt1.__hash__() == tt2.__hash__()
    6364        True
    6465
    65     Trees are usually immutable. However they inherits from
    66     :class:`sage.structure.list_clone.ClonableList`. So that they can be
    67     modified using the clone protocol:
     66    Trees are usually immutable. However they inherit from
     67    :class:`sage.structure.list_clone.ClonableList`, so that they can be
     68    modified using the clone protocol. Let us now see what this means.
    6869
    69     Trying to modify a non mutable tree raises an error::
     70    Trying to modify a non-mutable tree raises an error::
    7071
    7172        sage: tt1[1] = tt2
    7273        Traceback (most recent call last):
    class OrderedTree(AbstractClonableTree,  
    7677    Here is the correct way to do it::
    7778
    7879        sage: with tt2.clone() as tt2:
    79         ...    tt2[1] = tt1
     80        ....:     tt2[1] = tt1
    8081        sage: tt2
    8182        [[], [[], [[], []], [[], []]], [[], []]]
    8283
    8384    It is also possible to append a child to a tree::
    8485
    8586        sage: with tt2.clone() as tt3:
    86         ...    tt3.append(OrderedTree([]))
     87        ....:     tt3.append(OrderedTree([]))
    8788        sage: tt3
    8889        [[], [[], [[], []], [[], []]], [[], []], []]
    8990
    9091    Or to insert a child in a tree::
    9192
    9293        sage: with tt2.clone() as tt3:
    93         ...    tt3.insert(2, OrderedTree([]))
     94        ....:     tt3.insert(2, OrderedTree([]))
    9495        sage: tt3
    9596        [[], [[], [[], []], [[], []]], [], [[], []]]
    9697
    class OrderedTree(AbstractClonableTree,  
    108109
    109110        sage: tt1bis = OrderedTree(tt1)
    110111        sage: with tt1.clone() as tt1:
    111         ...    tt1[1] = tt1bis
     112        ....:     tt1[1] = tt1bis
    112113        sage: tt1
    113114        [[], [[], [[], []], [[], []]], [[], []]]
    114115        sage: tt1 == tt2
    class OrderedTree(AbstractClonableTree,  
    159160    Check that the hash value is correctly updated after modification::
    160161
    161162        sage: with tt2.clone() as tt2:
    162         ...    tt2[1,1] = tt1
     163        ....:     tt2[1,1] = tt1
    163164        sage: tt1.__hash__() == tt2.__hash__()
    164165        False
    165166    """
    class OrderedTree(AbstractClonableTree,  
    246247
    247248    def is_empty(self):
    248249        """
    249         Return if ``self`` is the empty tree
     250        Return if ``self`` is the empty tree.
    250251
    251         For ordered trees, returns always ``False``
     252        For ordered trees, returns always ``False``.
    252253
    253254        .. NOTE:: this is different from ``bool(t)`` which returns whether
    254255                  ``t`` has some child or not.