Problem:
Tree Walk Binary trees are defined recursively. A binary tree T is a structure defined on a finite set of nodes that either  contains no nodes, or  is composed of three disjoint sets of nodes: - a root node. - a binary tree called its left subtree. - a binary tree called its right subtree.   Your task is to write a program which perform tree walks (systematically traverse all nodes in a tree) based on the following algorithms:  Print the root, the left subtree and right subtree (preorder).  Print the left subtree, the root and right subtree (inorder).  Print the left subtree, right subtree and the root (postorder).  Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n -1. Input The first line of the input includes an integer n , the number of nodes of the tree. In the next n linen, the information of each node is given in the following format:  id left right   id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left ( right ) is indicated by -1  Output In the 1st line, print " Preorder ", and in the 2nd line print a list of node IDs obtained by the preorder tree walk. In the 3rd line, print " Inorder ", and in the 4th line print a list of node IDs obtained by the inorder tree walk. In the 5th line, print " Postorder ", and in the 6th line print a list of node IDs obtained by the postorder tree walk. Print a space character before each node ID. Constraints  1 ≤ n ≤ 25  Sample Input 1 9
0 1 4
1 2 3
2 -1 -1
3 -1 -1
4 5 8
5 6 7
6 -1 -1
7 -1 -1
8 -1 -1 Sample Output 1 Preorder
 0 1 2 3 4 5 6 7 8
Inorder
 2 1 3 0 6 5 7 4 8
Postorder
 2 3 1 6 7 5 8 4 0   Reference Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.

Solution (Python):
import sys

def main():
    n = input()
    tree = MyTree(n)
    for i in range(n):
        id_cn = map(int,raw_input().split())
        id_node = id_cn.pop(0)
        
        tree.add(id_node,None,id_cn)
    
    tree.search_children()
    tree.set_depth_height(tree.nodes[tree.id_root],0)

    print "Preorder"
    tree.preorder(tree.nodes[tree.id_root])
    print ""
    print "Inorder"
    tree.inorder(tree.nodes[tree.id_root])
    print ""
    print "Postorder"
    tree.postorder(tree.nodes[tree.id_root])
    print""

    
class MyTree():
    def __init__(self,num_nodes):
        self.nodes = [MyNode() for i in range(num_nodes)]
        self.id_root = None

    def add(self,id_node,id_parent,id_children):
        node = self.nodes[id_node]
        node.id_self = id_node
        node.id_parent = id_parent
        node.id_children = id_children
    
    def search_children(self):
        for node in self.nodes:
            if all(item==-1 for item in node.id_children):
                node.node_type = "leaf"
                node.degree = 0
            else:
                node.node_type = "internal node"
                l = node.id_children[0]
                r = node.id_children[1]
                if l == -1:
                    node.degree = 1
                    self.nodes[r].id_parent = node.id_self
                    self.nodes[r].sibling = l
                elif r == -1:
                    node.degree = 1
                    self.nodes[l].id_parent = node.id_self
                    self.nodes[l].sibling = r
                else:
                    node.degree = 2
                    self.nodes[l].id_parent = node.id_self
                    self.nodes[r].id_parent = node.id_self
                    self.nodes[l].sibling = r
                    self.nodes[r].sibling = l

        for node in self.nodes:
            if node.id_parent == None:
                node.id_parent = -1
                node.node_type = "root"
                self.id_root = node.id_self
                break

    def set_depth_height(self,node,depth):
        node.depth = depth
        l_height = []
        if all(item==-1 for item in node.id_children):
            node.height = 0
            return 0
        else:
            for item in node.id_children:
                if not item == -1:
                    l_height.append(self.set_depth_height(self.nodes[item],depth+1))
            height = max(l_height)+1
            node.height = height
            return height

    def preorder(self,node):
        sys.stdout.write(" {}".format(node.id_self))
        l,r = node.id_children
        if not l == -1:
            self.preorder(self.nodes[l])
        if not r == -1:
            self.preorder(self.nodes[r])    

    def inorder(self,node):
        l,r = node.id_children
        if not l == -1:
            self.inorder(self.nodes[l])
        sys.stdout.write(" {}".format(node.id_self))
        if not r == -1:
            self.inorder(self.nodes[r])

    def postorder(self,node):
        l,r = node.id_children
        if not l == -1:
            self.postorder(self.nodes[l])
        if not r == -1:
            self.postorder(self.nodes[r])
        sys.stdout.write(" {}".format(node.id_self))
                


class MyNode():
    def __init__(self):
        self.id_self = None
        self.id_parent = None
        self.id_children = None
        self.depth = None
        self.node_type = None
        self.n_children = 0
        self.sibling = -1
        self.degree = 0
        self.height = 0


if __name__ == "__main__":
    main()

Solution (Python):
import sys


def preorder(u):
    PRE.append(u)
    if TREE[u][1] != NIL:
        preorder(TREE[u][1])
    if TREE[u][2] != NIL:
        preorder(TREE[u][2])
        
        
def inorder(u):
    if TREE[u][1] != NIL:
        inorder(TREE[u][1])
    IN.append(u)
    if TREE[u][2] != NIL:
        inorder(TREE[u][2])


def postorder(u):
    if TREE[u][1] != NIL:
        postorder(TREE[u][1])
    if TREE[u][2] != NIL:
        postorder(TREE[u][2])
    POST.append(u)
        
        
if __name__=="__main__":
    NIL = -1
    n = int(sys.stdin.readline())
    TREE = [[NIL, NIL, NIL] for i in range(n)]
    root = set(range(n))
    PRE = []
    IN = []
    POST = []
    for inp in sys.stdin.readlines():
        inp = list(map(int, inp.split()))
        if inp[1] != NIL:
            TREE[inp[0]][1] = inp[1]
            TREE[inp[1]][0] = inp[1]
        if inp[2] != NIL:
            TREE[inp[0]][2] = inp[2]
            TREE[inp[2]][0] = inp[2]
        root -= set([inp[1], inp[2]])
    a = root.pop()
    preorder(a)
    inorder(a)
    postorder(a)
    print("Preorder")
    print(" " + " ".join(map(str, PRE)))
    print("Inorder")
    print(" " + " ".join(map(str, IN)))
    print("Postorder")
    print(" " + " ".join(map(str, POST)))

Solution (Python):
n = int(input())
tree = [0] * n
root = set(range(n))
for i in range(n):
    node_id, left, right = map(int, input().split())
    tree[node_id] = (left, right)
    root -= {left, right}
root_node = root.pop()


def preorder(i):
    if i == -1:
        return
    (left, right) = tree[i]
    yield i
    yield from preorder(left)
    yield from preorder(right)


def inorder(i):
    if i == -1:
        return
    (left, right) = tree[i]
    yield from inorder(left)
    yield i
    yield from inorder(right)


def postorder(i):
    if i == -1:
        return
    (left, right) = tree[i]
    yield from postorder(left)
    yield from postorder(right)
    yield i

print("Preorder\n ", end="")
print(*preorder(root_node))
print("Inorder\n ", end="")
print(*inorder(root_node))
print("Postorder\n ", end="")
print(*postorder(root_node))

Solution (Python):
import sys

I = 0
L = 1
R = 2
P = 3
B = 4
D = 5
H = 6

def getroot(A, id):
    if A[id][P] > -1:
        return getroot(A,A[id][P])
    return A[id][I]

def preorder(N,id,A):
    if id < 0:
        return
    A.append(id)
    preorder(N,N[id][L],A)
    preorder(N,N[id][R],A)

def inorder(N,id,A):
    if id < 0:
        return
    inorder(N,N[id][L],A)
    A.append(id)
    inorder(N,N[id][R],A)

def postorder(N,id,A):
    if id < 0:
        return
    postorder(N,N[id][L],A)
    postorder(N,N[id][R],A)
    A.append(id)


def main():

    """ ????????? """
    num = int(input().strip())
    istr = sys.stdin.read()
    nlist = list(istr.splitlines())
    
    nodes = [[i, -1, -1, -1, -1, 0, 0] for i in range(num)]

    for nstr in nlist:
        i = list(map(int,nstr.split()))
        n = nodes[i[I]]
        n[I] = i[I]
        if i[L] > -1:
            n[L] = i[L]
            nodes[n[L]][P] = i[I]
            nodes[n[L]][B] = i[R]
        if i[R] > -1:
            n[R] = i[R]
            nodes[n[R]][P] = i[I]
            nodes[n[R]][B] = i[L]


    r = getroot(nodes, 0)


    pre = [""]
    ino = [""]
    pos = [""]

    preorder(nodes,r,pre)
    inorder(nodes,r,ino)
    postorder(nodes,r,pos)

    print("Preorder")
    print(" ".join(map(str,pre)))
    print("Inorder")
    print(" ".join(map(str,ino)))
    print("Postorder")
    print(" ".join(map(str,pos)))
if __name__ == '__main__':
    main()

Solution (Python):
class Node():
    def __init__(self, id, left, right, parent=-1, degree=-1, type=None):
        self.id = id
        self.left = left
        self.right = right
        self.parent = parent
        self.degree = degree
        self.type = type
        
    def show(self):
        print 'node %d: parent = %d, degree = %d, %s' % (self.id, self.parent, self.degree, self.type)

class Stack():
    def __init__(self):
        self.el = []
    def add(self, el):
        self.el.append(el)
    def pop(self):
        return self.el.pop()
        
def hasChild(x):
    if x == -1:
        return 0
    return 1



dict = {}
a = []
n = int(raw_input())
for i in range(n):
    tmp = map(int, raw_input().split())
    dict[tmp[0]] = Node(tmp[0], tmp[1], tmp[2], degree=hasChild(tmp[1]) + hasChild(tmp[2]))

for i in range(n):
    a.append(dict[i])

for i in range(n):
    if not a[i].degree:
        continue
    a[a[i].left].parent = a[i].id
    a[a[i].right].parent = a[i].id

rootId = -1
for i in range(n):
    if a[i].parent != -1 and a[i].degree == 0:
        a[i].type = 'leaf'
    elif a[i].parent != -1 and a[i].degree > 0:
        a[i].type = 'internal node'
    else:
        a[i].type = 'root'
        rootId = a[i].id


print 'Preorder'
pos = rootId
st = Stack()
ans = []
while True:
    ans.append(pos)
    if len(ans) == n:
        break
    if a[pos].degree > 0:
        if a[pos].left != -1 and a[pos].right != -1:
            st.add(a[pos].right)
        if a[pos].left != -1:
            pos = a[pos].left
        elif a[pos].left == -1:
            pos = a[pos].right
    elif a[pos].degree == 0:
        pos = st.pop()
print '', ' '.join(map(str, ans))


print 'Inorder'
pos = rootId
st = Stack()
ans = []
while True:
    if a[pos].left != -1 and a[pos].left not in ans:
        if a[pos].right != -1:
            st.add(a[pos].right)
        st.add(pos)
        pos = a[pos].left
    elif a[pos].left == -1 and a[pos].right != -1 and a[pos].right not in ans:
        ans.append(pos)
        pos = a[pos].right
    else:
        ans.append(pos)
        if len(ans) == n:
            break
        pos = st.pop()    
print '', ' '.join(map(str, ans))


print 'Postorder'
pos = rootId
st = Stack()
ans = []
while True:
    if a[pos].left != -1 and a[pos].left not in ans:
        st.add(pos)
        if a[pos].right != -1:
            st.add(a[pos].right)
        pos = a[pos].left
    elif a[pos].left == -1 and a[pos].right != -1 and a[pos].right not in ans:
        st.add(pos)
        pos = a[pos].right
    else:
        ans.append(pos)
        if len(ans) == n:
            break
        pos = st.pop()
print '', ' '.join(map(str, ans))

Solution (Python):
n = int(input())
class Node(object):
    def __init__(self, p, l, r):
        self.p = p
        self.l = l
        self.r = r

nodes = [Node(None, None, None) for i in range(n)]

for i in range(n):
    id, left, right = map(int, input().split())
    nodes[id].l = left
    nodes[id].r = right
    if left != -1:
        nodes[left].p = i
    if right != -1:
        nodes[right].p = i

def pre(node,path):
    path.append(node)
    if nodes[node].l != -1:
        pre(nodes[node].l,path)
    if nodes[node].r != -1:
        pre(nodes[node].r,path)

def ino(node,path):
    if nodes[node].l != -1:
        ino(nodes[node].l,path)
    path.append(node)
    if nodes[node].r != -1:
        ino(nodes[node].r,path)

def post(node,path):
    if nodes[node].l != -1:
        post(nodes[node].l,path)
    if nodes[node].r != -1:
        post(nodes[node].r,path)
    path.append(node)

for ind, n in enumerate(nodes):
    if n.p == None:
        root = ind
        break
print('Preorder')
l = []
pre(root, l)
print(' ' +  ' '.join(map(str, l)))
print('Inorder')
l = []
ino(root, l)
print(' ' +  ' '.join(map(str, l)))
print('Postorder')
l = []
post(root,l)
print(' ' + ' '.join(map(str, l)))

Solution (Python):
N = int(input())
tree = [None for _ in range(N)]
root = set(range(N))

for i in range(N):
    i, l, r = map(int,input().split())
    tree[i] = (l, r)
    root -= {l, r}

root_node = root.pop()

def preorder(i):
    if i == -1:
        return
    (l, r) = tree[i]
    print(" {}".format(i), end = "")
    preorder(l)
    preorder(r)
    
def inorder(i):
    if i == -1:
        return
    (l, r) = tree[i]
    inorder(l)
    print(" {}".format(i), end = "")
    inorder(r)
    
def postorder(i):
    if i == -1:
        return
    (l, r) = tree[i]
    postorder(l)
    postorder(r)
    print(" {}".format(i), end = "")
    
print('Preorder')
preorder(root_node)
print()

print('Inorder')
inorder(root_node)
print()

print('Postorder')
postorder(root_node)
print()

Solution (Python):
class Node:
    def __init__(self, node_id, left_child, right_child):
        self.node_id = node_id
        self.parent = -1
        self.sibling = -1
        self.degree = 0
        self.depth = 0
        self.height = 0
        self.node_type = ''

        self.left_child = left_child
        self.right_child = right_child
        

def binarytrees():
    def input_node_list():
        n = int(input())

        for i in range(n):
            node_id, left_child, right_child = list(map(int, input().split()))

            node = Node(node_id, left_child, right_child)
            node_list.append(node)

        node_list.sort(key = lambda node: node.node_id)

    def calc_parent_sibling_degree():
        if node.left_child != -1:
            node_list[node.left_child].parent = node.node_id
            node_list[node.left_child].sibling = node.right_child
            node.degree += 1

        if node.right_child != -1:
            node_list[node.right_child].parent = node.node_id
            node_list[node.right_child].sibling = node.left_child
            node.degree += 1

    def calc_depth(node_id):
        if  node_list[node_id].parent == -1:
            return 0
        else:
            return calc_depth(node_list[node_id].parent) + 1

    def calc_height(node_id):
        if node_list[node_id].degree == 0:
            return 0
        else:
            left_height = right_height = 0

            if node_list[node_id].left_child != -1:
                left_height = calc_height(node_list[node_id].left_child)
            if node_list[node_id].right_child != -1:
                right_height = calc_height(node_list[node_id].right_child)

            return max(left_height, right_height) + 1

    def calc_node_type():
        if node.depth == 0:
            node.node_type = 'root'
        elif node.height == 0:
            node.node_type = 'leaf'
        else:
            node.node_type = 'internal node'

    def show_node_info():
        print('node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'
            .format(node.node_id, node.parent, node.sibling,
            node.degree, node.depth, node.height, node.node_type))

    node_list = []
    input_node_list()

    for node in node_list:
        calc_parent_sibling_degree()

    
    
    

    

    

    return node_list

def treewalk():
    def show_preorder(node_id):
        current_node = node_list[node_id]

        print(' {}'.format(current_node.node_id), end='')

        if current_node.left_child != -1:
            show_preorder(current_node.left_child)
        if current_node.right_child != -1:
            show_preorder(current_node.right_child)

    def show_inorder(node_id):
        current_node = node_list[node_id]

        if current_node.left_child != -1:
            show_inorder(current_node.left_child)

        print(' {}'.format(current_node.node_id), end='')

        if current_node.right_child != -1:
            show_inorder(current_node.right_child)

    def show_postorder(node_id):
        current_node = node_list[node_id]

        if current_node.left_child != -1:
            show_postorder(current_node.left_child)
        if current_node.right_child != -1:
            show_postorder(current_node.right_child)

        print(' {}'.format(current_node.node_id), end='')

    node_list = binarytrees()

    root_id = 0
    for node in node_list:
        if node.parent == -1:
            root_id = node.node_id
    
    print('Preorder')
    show_preorder(root_id)
    print('')

    print('Inorder')
    show_inorder(root_id)
    print('')

    print('Postorder')
    show_postorder(root_id)
    print('')

if __name__ == '__main__':
    treewalk()

Solution (Python):
class Node():
    def __init__(self, node_id, left, right):
        self.node_id    =   node_id
        self.left       =   left
        self.right      =   right

    def pre_order_search(self):
        l = self.left
        r = self.right
        print(" " + str(self.node_id), end="")
        if l != -1:
            tree[l].pre_order_search()
        if r != -1:
            tree[r].pre_order_search()

    def in_order_search(self):
        l = self.left
        r = self.right
        if l != -1:
            tree[l].in_order_search()
        print(" " + str(self.node_id), end="")
        if r != -1:
            tree[r].in_order_search()

    def post_order_search(self):
        l = self.left
        r = self.right
        if l != -1:
            tree[l].post_order_search()
        if r != -1:
            tree[r].post_order_search()
        print(" " + str(self.node_id), end="")

n = int(input())
tree = [None for i in range(n)]
root_set = set(range(n))

for i in range(n):
    node_id, left, right = map(int, input().split())
    tree[node_id] = Node(node_id, left, right)
    root_set -= set([left, right])
root = root_set.pop()

print("Preorder")
tree[root].pre_order_search()
print()

print("Inorder")
tree[root].in_order_search()
print()

print("Postorder")
tree[root].post_order_search()
print()

Solution (Python):
class Node():
    def __init__(self, node_id, left, right):
        self.node_id    =   node_id
        self.left       =   left
        self.right      =   right

    def pre_order_search(self):
        l = self.left
        r = self.right
        print("",self.node_id, end="")
        if l != -1:
            tree[l].pre_order_search()
        if r != -1:
            tree[r].pre_order_search()

    def in_order_search(self):
        l = self.left
        r = self.right
        if l != -1:
            tree[l].in_order_search()
        print("",self.node_id, end="")
        if r != -1:
            tree[r].in_order_search()

    def post_order_search(self):
        l = self.left
        r = self.right
        if l != -1:
            tree[l].post_order_search()
        if r != -1:
            tree[r].post_order_search()
        print("",self.node_id, end="")

n = int(input())
tree = [None for i in range(n)]
root_set = set(range(n))

for i in range(n):
    node_id, left, right = map(int, input().split())
    tree[node_id] = Node(node_id, left, right)
    root_set -= set([left, right])
root = root_set.pop()

print("Preorder")
tree[root].pre_order_search()
print()

print("Inorder")
tree[root].in_order_search()
print()

print("Postorder")
tree[root].post_order_search()
print()

Solution (Python):
class Node():
    def __init__(self, node_id, left, right):
        self.node_id    =   node_id
        self.left       =   left
        self.right      =   right

    def pre_order_search(self):
        l = self.left
        r = self.right
        print("",self.node_id, end="")
        if l != -1:
            tree[l].pre_order_search()
        if r != -1:
            tree[r].pre_order_search()

    def in_order_search(self):
        l = self.left
        r = self.right
        if l != -1:
            tree[l].in_order_search()
        print("",self.node_id, end="")
        if r != -1:
            tree[r].in_order_search()

    def post_order_search(self):
        l = self.left
        r = self.right
        if l != -1:
            tree[l].post_order_search()
        if r != -1:
            tree[r].post_order_search()
        print("",self.node_id, end="")

n = int(input())
tree = [None for i in range(n)]
root_set = set(range(n))

for i in range(n):
    node_id, left, right = map(int, input().split())
    tree[node_id] = Node(node_id, left, right)
    root_set -= set([left, right])
root = root_set.pop()

print("Preorder")
tree[root].pre_order_search()
print("")

print("Inorder")
tree[root].in_order_search()
print()

print("Postorder")
tree[root].post_order_search()
print()

Solution (Python):
class Node():
    def __init__(self, node_id, left, right):
        self.node_id    =   node_id
        self.left       =   left
        self.right      =   right

    def pre_order_search(self):
        l = self.left
        r = self.right
        print("",self.node_id, end="")
        if l != -1:
            tree[l].pre_order_search()
        if r != -1:
            tree[r].pre_order_search()

    def in_order_search(self):
        l = self.left
        r = self.right
        if l != -1:
            tree[l].in_order_search()
        print("",self.node_id, end="")
        if r != -1:
            tree[r].in_order_search()

    def post_order_search(self):
        l = self.left
        r = self.right
        if l != -1:
            tree[l].post_order_search()
        if r != -1:
            tree[r].post_order_search()
        print("",self.node_id, end="")

n = int(input())
tree = [None for i in range(n)]
root_set = set(range(n))

for i in range(n):
    node_id, left, right = map(int, input().split())
    tree[node_id] = Node(node_id, left, right)
    root_set -= set([left, right])
root = root_set.pop()

print("Preorder")
tree[root].pre_order_search()
print("")

print("Inorder")
tree[root].in_order_search()
print("")

print("Postorder")
tree[root].post_order_search()
print("")

Solution (Python):
from collections import defaultdict
def preorder(here, conn, chain):
    if here == -1:
        return
    chain.append(here)
    if conn[here]:
        preorder(conn[here][0], conn, chain)
        preorder(conn[here][1], conn, chain)

def inorder(here, conn, chain):
    if here == -1:
        return
    if conn[here]:
        inorder(conn[here][0], conn, chain)
        chain.append(here)
        inorder(conn[here][1], conn, chain)

def postorder(here, conn, chain):
    if here == -1:
        return
    if conn[here]:
        postorder(conn[here][0], conn, chain)
        postorder(conn[here][1], conn, chain)
    chain.append(here)

query = int(input())
connect = defaultdict(list)
in_v = [0 for n in range(query + 1)]
for _ in range(query):
    here, left, right = (int(n) for n in input().split(" "))
    connect[here] = [left, right]
    in_v[left] += 1
    in_v[right] += 1
for i in range(query):
    if not in_v[i]:
        root = i
        break
preo = []
ino = []
posto = []
preorder(root, connect, preo)
inorder(root, connect, ino)
postorder(root, connect, posto)

print("Preorder")
print("", end = " ")
print(*preo)
print("Inorder")
print("", end = " ")
print(*ino)
print("Postorder")
print("", end = " ")
print(*posto)

Solution (Python):
N = int(input())
left  =  [-1 for i in range(N)]
right =  [-1 for i in range(N)]
root = sum(range(N)) - N - 1
 
for i in range(N):
    i, l, r = map(int, input().split())
    left[i] = l
    right[i] = r
    root -= (l + r)
 
def preorder(i):
    if i == -1:
        return
    print(' ', i, sep = '', end = '')
    preorder(left[i])
    preorder(right[i])
     
def inorder(i):
    if i == -1:
        return
    inorder(left[i])
    print(' ', i, sep = '', end = '')
    inorder(right[i])
     
def postorder(i):
    if i == -1:
        return
    postorder(left[i])
    postorder(right[i])
    print(' ', i, sep = '', end = '')
     
print('Preorder')
preorder(root)
print()
 
print('Inorder')
inorder(root)
print()
 
print('Postorder')
postorder(root)
print()

Solution (Python):
n = int(input())
left = [None for i in range(n)]
right = [None for i in range(n)]
root = sum(range(n)) - n - 1

for i in range(n):
    i, l, r = map(int, input().split())
    left[i] = l
    right[i] = r
    root -= (l + r)

def Preorder(i):
    if (i == -1):
        return
    print(" {}".format(i), end = "")
    Preorder(left[i])
    Preorder(right[i])
      
def Inorder(i):
    if (i == -1):
        return
    Inorder(left[i])
    print(" {}".format(i), end = "")
    Inorder(right[i])
      
def Postorder(i):
    if (i == -1):
        return
    Postorder(left[i])
    Postorder(right[i])
    print(" {}".format(i), end = "")

print("Preorder")
Preorder(root)
print()
  
print("Inorder")
Inorder(root)
print()
  
print("Postorder")
Postorder(root)
print()

Solution (Python):
n = int(input())
left = [None for i in range(n)]
right = [None for i in range(n)]
root = sum(range(n)) - n - 1

for i in range(n):
    i, l, r = map(int, input().split())
    left[i] = l
    right[i] = r
    root -= (l + r)

def Preorder(i):
    if i == -1:
        return
    print(" {}".format(i), end = "")
    Preorder(left[i])
    Preorder(right[i])

def Inorder(i):
    if i == -1:
        return
    Inorder(left[i])
    print(" {}".format(i), end = "")
    Inorder(right[i])

def Postorder(i):
    if i == -1:
        return
    Postorder(left[i])
    Postorder(right[i])
    print(" {}".format(i), end = "")

print("Preorder")
Preorder(root)
print()

print("Inorder")
Inorder(root)
print()

print("Postorder")
Postorder(root)
print()

Solution (Python):

import sys


def tree_walk(tree, root):
    preorder_walk(tree, root)
    inorder_walk(tree, root)
    postoder_walk(tree, root)


def preorder_walk(tree, root):
    print("Preorder")
    result = []

    def preorder_walk_rec(node):
        if node == -1:
            pass
        else:
            result.append(str(node))
            preorder_walk_rec(tree[node][1])
            preorder_walk_rec(tree[node][2])

    preorder_walk_rec(root)
    print(" " + " ".join(result))


def inorder_walk(tree, root):
    print("Inorder")
    result = []

    def inorder_walk_rec(node):
        if node == -1:
            pass
        else:
            inorder_walk_rec(tree[node][1])
            result.append(str(node))
            inorder_walk_rec(tree[node][2])

    inorder_walk_rec(root)
    print(" " + " ".join(result))


def postoder_walk(tree, root):
    print("Postorder")
    result = []

    def postoder_work_rec(node):
        if node == -1:
            pass
        else:
            postoder_work_rec(tree[node][1])
            postoder_work_rec(tree[node][2])
            result.append(str(node))

    postoder_work_rec(root)
    print(" " + " ".join(result))


def get_tree():
    n = int(input())
    tree = [[-1, -1, -1] for x in range(0, n)]
    for node in sys.stdin.readlines():
        _id, left, right = [int(x) for x in node.split()]
        if left >= 0:
            tree[left][0] = _id
            tree[_id][1] = left
        if right >= 0:
            tree[right][0] = _id
            tree[_id][2] = right
    return tree


def get_root(tree):
    for i, node in enumerate(tree):
        if node[0] == -1:
            return i
    raise ValueError


if __name__ == "__main__":
    tree = get_tree()
    tree_walk(tree, get_root(tree))

Solution (Python):


import sys
sys.setrecursionlimit(100000)

class Node():
    def __init__(self, ID=None, parent=-1, left=-1, right=-1):
        self.id = ID
        self.parent = parent
        self.left = left
        self.right = right

def preParse(u):
    if u == -1:
        return
    print(" " + str(u), end="")
    preParse(T[u].left)
    preParse(T[u].right)
    
def inParse(u):
    if u == -1:
        return
    inParse(T[u].left)
    print(" " + str(u), end="")
    inParse(T[u].right)
    
def postParse(u):
    if u == -1:
        return
    postParse(T[u].left)
    postParse(T[u].right)
    print(" " + str(u), end="")
    
    
if __name__ == '__main__':

    n = int(input())
    T = [Node() for i in range(n)]

    for _ in range(n):
        ID, left, right = list(map(int, input().split(" ")))
        T[ID].id = ID
        T[ID].left = left
        T[ID].right = right
        if left != -1:
            T[left].parent = ID
        if right != -1:
            T[right].parent = ID
    
    for node in T:
        if node.parent==-1:
            r = node.id
    
    print("Preorder")
    preParse(r)
    print()
        
    print("Inorder")
    inParse(r)
    print()
    
    print("Postorder")
    postParse(r)
    print()

Solution (Python):
class Tree:
    __slots__ = ['id', 'p', 'left', 'right', "type"]
    def __init__(self, id):
        self.id = id
        self.p = -1
        self.left = -1
        self.right = -1
        self.type = "leaf"
    def __str__(self):
        return f"node {self.id}: parent = {self.p}, left = {self.left}, right = {self.right}, type = {self.type}"
n = int(input())
tree = tuple(Tree(i) for i in range(n))
for _ in range(n):
    id, l, r = map(int, input().split())
    if l != -1:
        tree[id].left = l
        tree[l].p = id
    if r != -1:
        tree[id].right = r
        tree[r].p = id
root = 0
while tree[root].p != -1:
    root = tree[root].p
def preorder_tree_walk(id):
    print(f" {tree[id].id}", end="")
    if tree[id].left != -1:
        preorder_tree_walk(tree[id].left)
    if tree[id].right != -1:
        preorder_tree_walk(tree[id].right)
def inorder_tree_walk(id):
    if tree[id].left != -1:
        inorder_tree_walk(tree[id].left)
    print(f" {tree[id].id}", end="")
    if tree[id].right != -1:
        inorder_tree_walk(tree[id].right)
def postorder_tree_walk(id):
    if tree[id].left != -1:
        postorder_tree_walk(tree[id].left)
    if tree[id].right != -1:
        postorder_tree_walk(tree[id].right)
    print(f" {tree[id].id}", end="")
print("Preorder")
preorder_tree_walk(root)
print("\nInorder")
inorder_tree_walk(root)
print("\nPostorder")
postorder_tree_walk(root)
print()

Solution (Python):
import collections

nil = -1

def preParse(u):
    if u == nil:
        return None
    print(' {}'.format(u), end='')
    preParse(tree[u]['left'])
    preParse(tree[u]['right'])

def inParse(u):
    if u == nil:
        return None
    inParse(tree[u]['left'])
    print(' {}'.format(u), end='')
    inParse(tree[u]['right'])

def postParse(u):
    if u == nil:
        return None
    postParse(tree[u]['left'])
    postParse(tree[u]['right'])
    print(' {}'.format(u), end='')

if __name__ == '__main__':
    n = int(input())
    tree = collections.defaultdict(dict)
    roots = list()
    for _ in range(n):
        id_num, left, right = [int(x) for x in input().split()]
        tree[id_num]['left'] = left
        tree[id_num]['right'] = right
        if left != nil:
            tree[left]['parent'] = id_num
        if right != nil:
            tree[right]['parent'] = id_num
    
    for key, val in tree.items():
        if not 'parent' in tree[key]:
            roots.append(key)
    
    print('Preorder')
    preParse(roots[0])
    print()
    print('Inorder')
    inParse(roots[0])
    print()
    print('Postorder')
    postParse(roots[0])
    print()