Untitled

 avatar
unknown
plain_text
a year ago
781 B
3
Indexable
class T:
    def __init__(self, value, child=None):
        self.value = value
        self.child = []

def depth_order(root):
    if root is None:
        return []
    ans = []
    for i in sorted(root.child, key=lambda x: x.value, reverse=True):
        ans += depth_order(i)
    return [root.value] + ans


def from_list(parents):
    nodes = {}
    root = None
    for i in range(1, len(parents)+1):
        nodes[i] = T(i)

    for i in range(1, len(parents)+1):
        if parents[i-1] != -1:
            nodes[parents[i - 1]].child.append(nodes[i])
        else:
            root = nodes[i]

    return list(nodes.values()), root

n = int(input())
parents = list(map(int, input().split()))
ans = from_list(parents)
print(*depth_order(ans[1]))
Leave a Comment