Дадох само последователност на трасера от предварителен редбинарно дърво (например {a, b, d, c, e}) и задачата е да откриете последователността от реда в него. Pls ми прости, ако това е дублиращ въпрос .... благодаря
Отговори:
1 за отговор № 1Не мисля, че можете да откриете трасера, който се основава само на преходния маршрут за двукомпонентно дърво. Както казахте за бинарно дърво за търсене, сортирането ви ще ви даде заобикалящия траверс.
0 за отговор № 2
Подготвих функция в Python, за да получа преструктуриране от трасета на поход. Може би това ще ви помогне да се надяваме.
Например,
Ако въведохте такава пост Въведете traversal след поръчка: ACEDBHIGF
Предварителната подредба ще бъде Преминаването преди поръчка е GAECFTJOLP
Това ще бъде Траверсията по поръчка е ABCDEFGHI
def from_post_order(post_order_items, order_type="pre"):
bst = BinarySearchTree()
values = [item for item in post_order_items]
root = values[-1] # the last item in the post_order item is ROOT
bst.insert(root) # insert ROOT
values.pop(-1) # and remove it from post_order_items
left_child = [] # the left child of ROOT for Post-order
right_child = [] # the right child of ROOT for Post-order
for v in values:
if v > root:
right_child.append(v)
else:
left_child.append(v)
for i in range(len(left_child + right_child)):
if len(left_child) != 0:
bst.insert(left_child[-1]) # insert left child
left_child.pop(-1) # remove the inserted left child from the list
if len(right_child) != 0:
bst.insert(right_child[-1]) # insert right child
right_child.pop(-1) # remove the inserted right child from the list
if order_type == "pre":
print("The pre-order traversal is ")
bst.preorder(print)
elif order_type == "in":
print("The in-order traversal is ")
bst.inorder(print)
else:
print("The post-order traversal is ")
bst.postorder(print)