Is it always possible to turn one BST into another using tree rotations?

后端 未结 2 691
耶瑟儿~
耶瑟儿~ 2021-02-03 13:29

Given a set of values, it\'s possible for there to be many different possible binary search trees that can be formed from those values. For example, for the values 1, 2, and 3,

2条回答
  •  时光说笑
    2021-02-03 13:50

    For binary search trees this can actually be done in O(n).

    Any tree can be "straightened out", ie put into a form in which all nodes are either the root or a left child.

    This form is unique (reading down from root gives the ordering of the elements)

    A tree is straightened out as follows:

    • For any right child, perform a left rotation about itself. This decreases the number of right children by 1, so the tree is straightened out in O(n) rotations.

    If A can be straightened out into S in O(n) rotations, and B into S in O(n) rotations, then since rotations are reversible one can turn A -> S -> B in O(n) rotations.

提交回复
热议问题