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.



Sample input:
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:
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

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
input:
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

output:
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
"""

import sys


class Node(object):
    def __init__(self):
        # init node as a single leaf node.
        self.parent = -1
        self.children = []
        self.index = -1


def pre_parse(v):
    print(' ' + str(v.index), end='')
    if not v.children:
        return None
    left_child_idx = v.children[0]
    right_child_idx = v.children[1]

    if left_child_idx != -1:
        pre_parse(node_list[left_child_idx])

    if right_child_idx != -1:
        pre_parse(node_list[right_child_idx])

    return None


def in_parse(v):
    if not v.children:
        return None
    left_child_idx = v.children[0]
    right_child_idx = v.children[1]

    if left_child_idx != -1:
        in_parse(node_list[left_child_idx])

    print(' ' + str(v.index), end='')

    if right_child_idx != -1:
        in_parse(node_list[right_child_idx])

    return None


def post_parse(v):
    if not v.children:
        return None
    left_child_idx = v.children[0]
    right_child_idx = v.children[1]

    if left_child_idx != -1:
        post_parse(node_list[left_child_idx])

    if right_child_idx != -1:
        post_parse(node_list[right_child_idx])

    print(' ' + str(v.index), end='')

    return None


def generate_tree(_array):
    # add info of each node of a ordered tree
    for each in _array:
        idx, *children = [int(x) for x in each]
        # assert len(children) == 2 and idx >= 0
        node_list[idx].index = idx
        node_list[idx].children = children

        for child_idx in children:
            # non-existent node: no parent
            if child_idx == -1:
                continue
            node_list[child_idx].parent = idx

    # find root node
    root_idx = [x.index for x in node_list if x.parent == -1][0]
    root_node = node_list[root_idx]

    # tree walk in 3 ways
    print('Preorder')
    pre_parse(root_node)
    print('\n' + 'Inorder')
    in_parse(root_node)
    print('\n' + 'Postorder')
    post_parse(root_node)
    print('')

    return node_list


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    array_length = int(_input[0])
    array = list(map(lambda x: x.split(), _input[1:]))
    # assert len(array) == array_length

    node_list = [Node() for _ in range(array_length)]
    ans = generate_tree(_array=array)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
input:
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

output:
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
"""

import sys


class Node(object):
    def __init__(self):
        # init node as a single leaf node.
        self.parent = -1
        self.children = []
        self.index = -1


def pre_parse(v):
    print(' ' + str(v.index), end='')

    left_child_idx = v.children[0]
    right_child_idx = v.children[1]

    if left_child_idx != -1:
        pre_parse(node_list[left_child_idx])

    if right_child_idx != -1:
        pre_parse(node_list[right_child_idx])

    return None


def in_parse(v):
    left_child_idx = v.children[0]
    right_child_idx = v.children[1]

    if left_child_idx != -1:
        in_parse(node_list[left_child_idx])

    print(' ' + str(v.index), end='')

    if right_child_idx != -1:
        in_parse(node_list[right_child_idx])

    return None


def post_parse(v):
    left_child_idx = v.children[0]
    right_child_idx = v.children[1]

    if left_child_idx != -1:
        post_parse(node_list[left_child_idx])

    if right_child_idx != -1:
        post_parse(node_list[right_child_idx])

    print(' ' + str(v.index), end='')

    return None


def generate_tree(_array):
    # add info of each node of a ordered tree
    for each in _array:
        idx, *children = [int(x) for x in each]
        # assert len(children) == 2 and idx >= 0
        node_list[idx].index = idx
        node_list[idx].children = children

        for child_idx in children:
            # non-existent node: no parent
            if child_idx == -1:
                continue
            node_list[child_idx].parent = idx

    # find root node
    root_idx = [x.index for x in node_list if x.parent == -1][0]
    root_node = node_list[root_idx]

    # tree walk in 3 ways
    print('Preorder')
    pre_parse(root_node)
    print('\n' + 'Inorder')
    in_parse(root_node)
    print('\n' + 'Postorder')
    post_parse(root_node)
    print('')

    return node_list


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    array_length = int(_input[0])
    array = list(map(lambda x: x.split(), _input[1:]))
    # assert len(array) == array_length

    node_list = [Node() for _ in range(array_length)]
    ans = generate_tree(_array=array)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
input:
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

output:
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
"""

import sys


class Node(object):
    def __init__(self):
        # init node as a single leaf node.
        self.parent = -1
        self.children = []
        self.index = -1


def pre_parse(v):
    print(' ' + str(v.index), end='')

    left_child_idx = v.children[0]
    right_child_idx = v.children[1]

    if left_child_idx != -1:
        pre_parse(node_list[left_child_idx])

    if right_child_idx != -1:
        pre_parse(node_list[right_child_idx])

    return v.index


def in_parse(v):
    left_child_idx = v.children[0]
    right_child_idx = v.children[1]

    if left_child_idx != -1:
        in_parse(node_list[left_child_idx])

    print(' ' + str(v.index), end='')

    if right_child_idx != -1:
        in_parse(node_list[right_child_idx])

    return v.index


def post_parse(v):
    left_child_idx = v.children[0]
    right_child_idx = v.children[1]

    if left_child_idx != -1:
        post_parse(node_list[left_child_idx])

    if right_child_idx != -1:
        post_parse(node_list[right_child_idx])

    print(' ' + str(v.index), end='')

    return v.index


def generate_tree(_array):
    # add info of each node of a ordered tree
    for each in _array:
        idx, *children = [int(x) for x in each]
        # assert len(children) == 2 and idx >= 0
        node_list[idx].index = idx
        node_list[idx].children = children

        for child_idx in children:
            # non-existent node: no parent
            if child_idx == -1:
                continue
            node_list[child_idx].parent = idx

    # find root node
    root_idx = [x.index for x in node_list if x.parent == -1][0]
    root_node = node_list[root_idx]

    # tree walk in 3 ways
    print('Preorder')
    pre_parse(root_node)
    print('\n' + 'Inorder')
    in_parse(root_node)
    print('\n' + 'Postorder')
    post_parse(root_node)
    print('')

    return node_list


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    array_length = int(_input[0])
    array = list(map(lambda x: x.split(), _input[1:]))
    # assert len(array) == array_length

    node_list = [Node() for _ in range(array_length)]
    ans = generate_tree(_array=array)

Submission status: Accepted

Solution code:
class Node(object):
    """ ????????¨????????? """
    def __init__(self, parent, left, right):
        self.parent = parent
        self.left = left
        self.right = right
        self.height = None

    def get_type(self):
        if self.parent == -1:
            return 'root'
        elif self.left == -1 and self.right == -1:
            return 'leaf'
        else:
            return 'internal node'

    def get_depth(self):
        if self.parent == -1:
            return 0
        else:
            depth = 1
            t = Nodes[self.parent]
            while t.parent != -1:
                t = Nodes[t.parent]
                depth += 1
            return depth

    def get_height(self):
        if self.height:
            return self.height
        h_left = 0
        h_right = 0
        if self.left != -1:
            h_left = Nodes[self.left].get_height() + 1
        if self.right != -1:
            h_right = Nodes[self.right].get_height() + 1
        self.height = max(h_left, h_right)
        return self.height

    def get_degree(self):
        degree = 0
        if self.left != -1:
            degree += 1
        if self.right != -1:
            degree += 1
        return degree

    def get_sibling(self):
        if self.parent == -1:
            return -1
        p = Nodes[self.parent]
        if Nodes[p.left] != self and Nodes[p.left] != -1:
            return p.left
        if Nodes[p.right] != self and Nodes[p.right] != -1:
            return p.right


def process_node_data(data):
    """ ??\???????????????????????????????????¨?????????????????? """
    num_of_elem = len(data)
    if num_of_elem != 3:
        raise ValueError
    else:
        my_id, left, right = data
        Nodes[my_id].left = left
        if left != -1:
            Nodes[left].parent = my_id
        Nodes[my_id].right = right
        if right != -1:
            Nodes[right].parent = my_id


def walk_preorder(Nodes, current_id):
    results = []
    results.append(current_id)
    if Nodes[current_id].left != -1:
        results.append(walk_preorder(Nodes, Nodes[current_id].left))
    if Nodes[current_id].right != -1:
        results.append(walk_preorder(Nodes, Nodes[current_id].right))
    return results


def walk_inorder(Nodes, current_id):
    results = []
    if Nodes[current_id].left != -1:
        results.append(walk_inorder(Nodes, Nodes[current_id].left))
    results.append(current_id)
    if Nodes[current_id].right != -1:
        results.append(walk_inorder(Nodes, Nodes[current_id].right))
    return results


def walk_postorder(Nodes, current_id):
    results = []
    if Nodes[current_id].left != -1:
        results.append(walk_postorder(Nodes, Nodes[current_id].left))
    if Nodes[current_id].right != -1:
        results.append(walk_postorder(Nodes, Nodes[current_id].right))
    results.append(current_id)
    return results


def flatten(l):
    """ http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python """
    import collections
    for el in l:
        if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)):
            yield from flatten(el)
        else:
            yield el


if __name__ == '__main__':
    MAX_NODES = 25
    # ????´???? [Node(None, None, None)] * MAX_NODES ????????¨????????????????????????????????§??¨???
    Nodes = [Node(-1, None, None) for _ in range(MAX_NODES)]

    # ??????????????\???
    num_of_nodes = int(input())
    node_data = []
    for i in range(num_of_nodes):
        t = [int(x) for x in input().split(' ')]
        node_data.append(t)

    # ???????????????
    # ??¨???????????????
    for d in node_data:
        process_node_data(d)

    # ???????????????
    # ??¨???root????¢????
    root_id = -1
    for i, n in enumerate(Nodes):
        if n.parent == -1:
            root_id = i
            break

    print('Preorder')
    result = walk_preorder(Nodes, root_id)
    print(' {0}'.format(' '.join(map(str, flatten(result)))))

    print('Inorder')
    result = walk_inorder(Nodes, root_id)
    print(' {0}'.format(' '.join(map(str, flatten(result)))))

    print('Postorder')
    result = walk_postorder(Nodes, root_id)
    print(' {0}'.format(' '.join(map(str, flatten(result)))))

Submission status: Accepted

Solution code:

nil = -1

class Node:
    def __init__(self):
        self.parent = nil
        self.left = nil
        self.right = nil

def pre_tw(node):
    print(' ' + str(node), end = '')

    if tree[node].left != nil:
        pre_tw(tree[node].left)

    if tree[node].right != nil:
        pre_tw(tree[node].right)

def in_tw(node):
    if tree[node].left != nil:
        in_tw(tree[node].left)

    print(' ' + str(node), end = '')

    if tree[node].right != nil:
        in_tw(tree[node].right)

def post_tw(node):
    if tree[node].left != nil:
        post_tw(tree[node].left)

    if tree[node].right != nil:
        post_tw(tree[node].right)

    print(' ' + str(node), end = '')


n = int(input())

tree = [Node() for i in range(n)]

for i in range(n):
    line = [int(j) for j in input().split()]
    id_t = line[0]
    left = line[1]
    right = line[2]

    if left != nil:
        tree[id_t].left = left
        tree[left].parent = id_t
    if right != nil:
        tree[id_t].right = right
        tree[right].parent = id_t

for i in range(n):
    if tree[i].parent == nil:
        root = i
        break

print('Preorder')
pre_tw(root)
print('')

print('Inorder')
in_tw(root)
print('')

print('Postorder')
post_tw(root)
print('')

Submission status: Accepted

Solution code:

class Tree:
    def __init__(self,parent,left,right):
        self.parent = parent
        self.left = left
        self.right = right


def preparse(u):
    if u == -1: return
    print(" ", end="")
    print(u, end="")
    preparse(trees[u].left)
    preparse(trees[u].right)


def inparse(u):
    if u == -1: return
    #???????????????????§????
    inparse(trees[u].left)
    #??¨???
    print(" ", end="")
    print(u, end="")
    #??????????§????
    inparse(trees[u].right)
    

def postparse(u):
    if u == -1: return
    #???????????????????§????
    postparse(trees[u].left)
    #??????????§????
    postparse(trees[u].right)
    #??¨???
    print(" ", end="")
    print(u, end="")


N = int(input())
# ?????????
trees = [Tree(-1,-1,-1) for i in range(N)]
for i in range(N):
    l = list(map(int, input().split()))
    no = l[0]
    left = l[1]
    right = l[2]
    trees[no].left = left
    trees[no].right = right
    if left != -1: trees[left].parent = no
    if right != -1: trees[right].parent = no

r = 0
for i in range(N):
    if trees[i].parent == -1:
        r = i

print("Preorder")
preparse(r)
print("")
print("Inorder")
inparse(r)
print("")
print("Postorder")
postparse(r)
print("")

Submission status: Accepted

Solution code:
import sys

def walk(T, nid, order):
  if nid < 0: return
  pid, lid, rid = T[nid]

  if order == "pre":
    sys.stdout.write(" " + str(nid))
    walk(T, lid, order)
    walk(T, rid, order)
  elif order == "in":
    walk(T, lid, order)
    sys.stdout.write(" " + str(nid))
    walk(T, rid, order)
  else:
    walk(T, lid, order)
    walk(T, rid, order)
    sys.stdout.write(" " + str(nid))

T = {}
for i in range(int(input())):
  nid, lid, rid = map(int, input().split())
  T[nid] = [-1, lid, rid]

# set parent
for nid in T:
  pid, lid, rid = T[nid]
  if lid >= 0: T[lid][0] = nid
  if rid >= 0: T[rid][0] = nid

# select root
for nid in T:
  if T[nid][0] == -1: root_id = nid

print("Preorder"),  walk(T, root_id, "pre"),  print()
print("Inorder"),   walk(T, root_id, "in"),   print()
print("Postorder"), walk(T, root_id, "post"), print()

Submission status: Accepted

Solution code:
class Tree:
    def __init__(self, n):
        self.n = n
        self.nodes = [Node(i) for i in range(n)]
        self.root = -1

    def set_tree(self):
        for _ in range(self.n):
            i_str = [int(i) for i in input().split()]
            for i in range(2):
                if i_str[i+1] != -1:
                    if i == 0:
                        self.nodes[i_str[0]].left = i_str[1]
                    else:
                        self.nodes[i_str[0]].right = i_str[2]
                    self.nodes[i_str[i+1]].parent = i_str[0]

    def set_root(self):
        for tn in self.nodes:
            if tn.parent == -1:
                self.root = tn.id
                return tn.id

    def preorder(self, node):
        print(' ' + str(self.nodes[node].id), end='')
        if self.nodes[node].left != -1:
            self.preorder(self.nodes[node].left)
        if self.nodes[node].right != -1:
            self.preorder(self.nodes[node].right)

    def inorder(self, node):
        if self.nodes[node].left != -1:
            self.inorder(self.nodes[node].left)
        print(' ' + str(self.nodes[node].id), end='')
        if self.nodes[node].right != -1:
            self.inorder(self.nodes[node].right)

    def postorder(self, node):
        if self.nodes[node].left != -1:
            self.postorder(self.nodes[node].left)
        if self.nodes[node].right != -1:
            self.postorder(self.nodes[node].right)
        print(' ' + str(self.nodes[node].id), end='')

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

if __name__ == '__main__':
    tree = Tree(int(input()))
    tree.set_tree()
    root = tree.set_root()
    print("Preorder")
    tree.preorder(root)
    print()
    print('Inorder')
    tree.inorder(root)
    print()
    print('Postorder')
    tree.postorder(root)
    print()

Submission status: Accepted

Solution code:
class Node:
    def __init__(self, num, left,  right):
        self.id = num
        self.left = left
        self.right = right
        self.parent = -1
        self.brother = -1
        if self.left== -1 and self.right==-1:
        	self.child = 0
        elif self.left != -1 and self.right!=-1:
        	self.child = 2
        else:
        	self.child = 1
        self.depth = 0
        self.height = 0
        self.type = None

    def show_info(self):
        print('node {0}: parent = {1}, sibling = {2}, degree = {3}, depth = {4}, height = {5}, {6}'.format(self.id, self.parent, self.brother, self.child, self.depth, self.height, self.type))

def SetNode(I_Line):
	L = list(map(int, I_Line.split()))
	num = L[0]
	left = L[1]
	right = L[2]
	node = Node(num, left, right)
	T[num] = node
	if left != -1:
		T[-1] -= left
	if right != -1:
		T[-1] -= right

def setPBD(i,p,b,d): #??????????????????
    node = T[i]
    node.parent = p
    node.brother = b
    node.depth = d
    if node.parent == -1:
        node.type = "root"
    elif node.child == 0:
        node.type = "leaf"
    else:
        node.type = "internal node"
    if node.left != -1:
        setPBD(node.left, i, node.right, node.depth + 1)
    if node.right != -1:
        setPBD(node.right, i, node.left, node.depth + 1)

def setH(i): #??????????????????
    node = T[i]
    if node.left == -1:
        leftheight = 0
    else:
        leftheight = setH(node.left) + 1
    if node.right == -1:
        rightheight = 0
    else:
        rightheight = setH(node.right) + 1
    node.height = max(leftheight, rightheight)
    return node.height

n = int(input())
T = [None] * n
T.append(int(n * (n-1)/2))
for i in range(n):
    x = input()
    SetNode(x)

root = T[-1]
setPBD(root, -1, -1, 0)
setH(root)
T.pop()

pre = []
def preoder(x): #??????????????????
	if x == -1: return
	else:
            node = T[x]
            pre.append(str(x))
            preoder(node.left)
            preoder(node.right)
print("Preorder")
preoder(root)
print(" " + " ".join(pre))

ino = []
def inoder(x):
	if x == -1: return
	else:
            node = T[x]
            inoder(node.left)
            ino.append(str(x))
            inoder(node.right)
print("Inorder")
inoder(root)
print(" " + " ".join(ino))

pos = []
def postoder(x):
	if x == -1: return
	else:
            node = T[x]
            postoder(node.left)
            postoder(node.right)
            pos.append(str(x))
print("Postorder")
postoder(root)
print(" " + " ".join(pos))

Submission status: Accepted

Solution code:
# coding=utf-8

class Node:
    def __init__(self, ID, left, right):
        ### output information ###
        self.id = ID
        self.parent = -1 #initialize
        self.sibling = -1 #initialize
        self.degree = -1 #initialize
        self.depth = -1 #initialize
        self.height = -1 #initialize
        self.type = None #initialize

        ### other information ###
        self.left = left
        self.right = right

def calc_depth(i):
    global node_list

    if node_list[i].depth != -1:
        return node_list[i].depth

    depth = 0
    if node_list[i].parent != -1:
        depth = calc_depth(node_list[i].parent) + 1

    node_list[i].depth = depth
    return depth


def calc_height(i):
    global node_list

    if node_list[i].height != -1:
        return node_list[i].height

    h1 = h2 = 0
    if node_list[i].right != -1:
        h1 = calc_height(node_list[i].right) + 1
    if node_list[i].left != -1:
        h2 = calc_height(node_list[i].left) + 1

    height = max(h1, h2)
    node_list[i].height = height
    return height

def pre_order(node):
    global node_list
    global pre_ordered_node_list

    if node == -1:
        return None
    pre_ordered_node_list.append(node)
    pre_order(node_list[node].left)
    pre_order(node_list[node].right)

def in_order(node):
    global node_list
    global in_ordered_node_list

    if node == -1:
        return None
    in_order(node_list[node].left)
    in_ordered_node_list.append(node)
    in_order(node_list[node].right)

def post_order(node):
    global node_list
    global post_ordered_node_list

    if node == -1:
        return None
    post_order(node_list[node].left)
    post_order(node_list[node].right)
    post_ordered_node_list.append(node)

n = int(input())
data = [tuple(map(int, input().split())) for x in range(n)]
node_list = []
root_node = None
pre_ordered_node_list = []
in_ordered_node_list = []
post_ordered_node_list = []

for data_row in data:
    ID, left, right = data_row
    node = Node(ID, left, right)
    node_list.append(node)

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

for i, node in enumerate(node_list):
    left = node.left
    right = node.right
    degree = 0

    ### child information ###
    if left != -1:
        degree += 1
        node_list[left].parent = i
        node_list[left].sibling = right

    if right != -1:
        degree += 1
        node_list[right].parent = i
        node_list[right].sibling = left

    ### self information ###
    node.degree = degree

for i in range(n):
    calc_depth(i)
    calc_height(i)

    node = node_list[i]

    if node.depth == 0:
        node.type = 'root'
        root_node = node.id
    elif node.height == 0:
        node.type = 'leaf'
    else:
        node.type = 'internal node'

    #print("node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}".format(node.id, node.parent, node.sibling, node.degree, node.depth, node.height, node.type))

### Tree Walk ###
pre_order(root_node)
in_order(root_node)
post_order(root_node)

print("Preorder")
print("", *pre_ordered_node_list)
print("Inorder")
print("", *in_ordered_node_list)
print("Postorder")
print("", *post_ordered_node_list)

Submission status: Accepted

Solution code:
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()

Submission status: Accepted

Solution code:
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)))

Submission status: Accepted

Solution code:
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))