Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
957 B
2
Indexable
Never
#python
class Node:
    def __init__(self, key, left, right):
        self.key = key
        self.left = left
        self.right = right

def inorder(root):
    if root.key == -1:
        return []
    return inorder(root.left) + [root.key] + inorder(root.right)


def preorder(root):
    if root.key == -1:
        return []
    return [root.key] + preorder(root.left) + preorder(root.right)


def postorder(root):
    if root.key == -1:
        return []
    return postorder(root.left) + postorder(root.right) + [root.key]


n = int(input())
nodes = []
for i in range(n):
    data = list(map(int, input().split()))
    nodes.append(Node(data[0], data[1], data[2]))

for i in range(n):
    left = nodes[i].left
    right = nodes[i].right
    nodes[i].left = nodes[left] if left != -1 else Node(-1, 0, 0)
    nodes[i].right = nodes[right] if right != -1 else Node(-1, 0, 0)

print(*inorder(nodes[0]))
print(*preorder(nodes[0]))
print(*postorder(nodes[0]))
Leave a Comment