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: Wrong Answer

Solution code:
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
        print(self.node_id, self.left, 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()

Submission status: Wrong Answer

Solution code:
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)
for _ in range(query):
    here, left, right = (int(n) for n in input().split(" "))
    connect[here] = [left, right]
preo = []
ino = []
posto = []
preorder(0, connect, preo)
inorder(0, connect, ino)
postorder(0, connect, posto)

print("Preorder")
print(*preo)
print("Inorder")
print(*ino)
print("Postorder")
print(*posto)

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

Solution code:
def s(x):print(_,x,end='')
def p(u):
 if u+1:s(u);p(T[u]);p(T[u+N])
def i(u):
 if u+1:i(T[u]);s(u);i(T[u+N])
def o(u):
 if u+1:o(T[u]);o(T[u+N]);s(u)
N=int(input())
T=[0,0]*N
for _ in[0]*N:
 a,b,c=map(int,input().split())
 T[a],T[a+N]=b,c
r=(set(range(N))-set(T)).pop()
print('Preorder');p(r)
print('\nInorder');i(r)
print('\nPostorder');o(r)
print()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat May 19 19:34:44 2018
ALDS1_7_B
@author: maezawa
"""

n = int(input())

parent = [-1 for _ in range(n)]
left = [-1 for _ in range(n)]
right = [-1 for _ in range(n)]
height = [None for _ in range(n)]
depth = [None for _ in range(n)]

def set_parent():
    global parent
    for i in range(n):
        if left[i] != -1:
            parent[left[i]] = i
        if right[i] != -1:
            parent[right[i]] = i

    
def set_depth(i, p):
    global depth
    if depth[i] != None:
        return
    depth[i] = p
    if right[i] != None:
        set_depth(right[i], p)
    if left[i] != None:
        set_depth(left[i], p+1)
       
def get_depth(i):
    global depth
    if depth[i] != None:
        return depth[i]
    d = 0
    u = i
    while parent[u] != -1:
        u = parent[u]
        d += 1
    depth[i] = d
    return d

def set_height(u):
    global height
    h1 = 0
    h2 = 0
    if right[u] != -1:
        h1 = set_height(right[u])+1
    if left[u] != -1:
        h2 = set_height(left[u])+1
    height[u] = max(h1, h2)
    return height[u]    

def get_sib(i):
    if right[parent[i]] == i:
        return left[parent[i]]
    else:
        return right[parent[i]]
    
def get_deg(i):
    deg = 0
    if right[i] != -1:
        deg += 1
    if left[i] != -1:
        deg += 1
    return deg    

def get_height(i):
    return height[i]

def preparse(i):
    if i == -1:
        return
    print('{} '.format(i), end='')
    preparse(left[i])
    preparse(right[i])
    
def inparse(i):
    if i == -1:
        return
    inparse(left[i])
    print('{} '.format(i), end='')
    preparse(right[i])
 
def postparse(i):
    if i == -1:
        return
    postparse(left[i])
    postparse(right[i])
    print('{} '.format(i), end='')

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

set_parent()
root = parent.index(-1)
print('Preorder')
preparse(root)
print()
print('Inorder')
inparse(root)
print()
print('Postorder')
postparse(root)
print()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat May 19 19:34:44 2018
ALDS1_7_B
@author: maezawa
"""

n = int(input())

parent = [-1 for _ in range(n)]
left = [-1 for _ in range(n)]
right = [-1 for _ in range(n)]
height = [None for _ in range(n)]
depth = [None for _ in range(n)]

def set_parent():
    global parent
    for i in range(n):
        if left[i] != -1:
            parent[left[i]] = i
        if right[i] != -1:
            parent[right[i]] = i

    
def set_depth(i, p):
    global depth
    if depth[i] != None:
        return
    depth[i] = p
    if right[i] != None:
        set_depth(right[i], p)
    if left[i] != None:
        set_depth(left[i], p+1)
       
def get_depth(i):
    global depth
    if depth[i] != None:
        return depth[i]
    d = 0
    u = i
    while parent[u] != -1:
        u = parent[u]
        d += 1
    depth[i] = d
    return d

def set_height(u):
    global height
    h1 = 0
    h2 = 0
    if right[u] != -1:
        h1 = set_height(right[u])+1
    if left[u] != -1:
        h2 = set_height(left[u])+1
    height[u] = max(h1, h2)
    return height[u]    

def get_sib(i):
    if right[parent[i]] == i:
        return left[parent[i]]
    else:
        return right[parent[i]]
    
def get_deg(i):
    deg = 0
    if right[i] != -1:
        deg += 1
    if left[i] != -1:
        deg += 1
    return deg    

def get_height(i):
    return height[i]

def preparse(i):
    if i == -1:
        return
    print(' {}'.format(i), end='')
    preparse(left[i])
    preparse(right[i])
    
def inparse(i):
    if i == -1:
        return
    inparse(left[i])
    print(' {}'.format(i), end='')
    preparse(right[i])
 
def postparse(i):
    if i == -1:
        return
    postparse(left[i])
    postparse(right[i])
    print(' {}'.format(i), end='')

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

set_parent()
root = parent.index(-1)
print('Preorder')
preparse(root)
print()
print('Inorder')
inparse(root)
print()
print('Postorder')
postparse(root)
print()

Submission status: Wrong Answer

Solution code:
def pre_parse(node_id):
    if node_id == -1:
        return
    print(node_id, end=" ")
    pre_parse(node_info_list[node_id]['left'])
    pre_parse(node_info_list[node_id]['right'])


def in_parse(node_id):
    if node_id == -1:
        return
    in_parse(node_info_list[node_id]['left'])
    print(node_id, end=" ")
    in_parse(node_info_list[node_id]['right'])


def post_parse(node_id):
    if node_id == -1:
        return
    post_parse(node_info_list[node_id]['left'])
    post_parse(node_info_list[node_id]['right'])
    print(node_id, end=" ")


n = int(input())
node_info_list = [{
    'parent': -1,
    'left': -1,
    'right': -1,
} for _ in range(n)]

for _ in range(n):
    node_id, left, right = list(map(int, input().split()))
    node_info_list[node_id]['left'] = left
    node_info_list[node_id]['right'] = right
    node_info_list[left]['parent'] = node_id
    node_info_list[right]['parent'] = node_id

root_node_id = -1

for i in range(n):
    if node_info_list[i]['parent'] == -1:
        root_node_id = i
        break

pre_parse(root_node_id)
print("")
in_parse(root_node_id)
print("")
post_parse(root_node_id)

Submission status: Wrong Answer

Solution code:
n = int(input())
root = set(range(n))
nodes = [0 for i in range(n)]
for i in range(n):
    node = list(map(int, input().split()))
    children = node[1:3]
    root -= set(children)
    nodes[node[0]] = children

def preorder(id):
    if(id == -1):
        return
    order.append(id)
    preorder(nodes[id][0])
    preorder(nodes[id][1])

def inorder(id):
    if(id == -1):
        return
    inorder(nodes[id][0])
    order.append(id)
    inorder(nodes[id][1])

def postorder(id):
    if(id == -1):
        return
    postorder(nodes[id][0])
    postorder(nodes[id][1])
    order.append(id)

order = []
preorder(list(root)[0])
print(*order)
order = []
inorder(list(root)[0])
print(*order)
order = []
postorder(list(root)[0])
print(*order)

Submission status: Wrong Answer

Solution code:
class Tree:
    def __init__(self, ary):
        self.nodes = [
            Node(node, self) for node in sorted(ary, key=lambda x: x[0])
        ]
        [node.set() for node in self.nodes]
        for node in self.nodes:
            if node.parent == -1:
                self.root = node
                break
        self.root.set_depth(0)
        self.root.set_height()

    def output(self):
        [node.output() for node in self.nodes]

    def preorder(self):
        print('Preorder')
        self.root.preorder()
        print()

    def inorder(self):
        print('Inorder')
        self.root.inorder()
        print()

    def postorder(self):
        print('Postorder')
        self.root.postorder()
        print()


class Node:
    def __init__(self, node, tree):
        self.tree = tree
        self.no = node[0]
        self.left = node[1]
        self.right = node[2]
        self.parent = -1
        self.sibling = -1
        self.degree = 0

    def set(self):
        if self.left > -1:
            self.tree.nodes[self.left].parent = self.no
            if self.right > -1:
                self.tree.nodes[self.right].sibling = self.left
            self.degree += 1

        if self.right > -1:
            self.tree.nodes[self.right].parent = self.no
            if self.left > -1:
                self.tree.nodes[self.left].sibling = self.right
            self.degree += 1

    def set_depth(self, d):
        self.depth = d
        if self.left > -1:
            self.tree.nodes[self.left].set_depth(d + 1)
        if self.right > -1:
            self.tree.nodes[self.right].set_depth(d + 1)

    def set_height(self):
        if self.degree == 0:
            self.height = 0
        else:
            self.tree.nodes[self.right].set_height()
            self.tree.nodes[self.left].set_height()
            self.height = 1 + max(self.tree.nodes[self.right].height,
                                  self.tree.nodes[self.left].height)

    def output(self):
        if self.parent == -1:
            kind = 'root'
        elif self.degree == 0:
            kind = 'leaf'
        else:
            kind = 'internal node'
        print(
            'node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'.
            format(self.no, self.parent, self.sibling, self.degree, self.depth,
                   self.height, kind))

    def preorder(self):
        print(' {}'.format(self.no), end='')
        if self.left > -1:
            self.tree.nodes[self.left].preorder()
        if self.right > -1:
            self.tree.nodes[self.right].preorder()

    def inorder(self):
        if not self.left > -1:
            print(' {}'.format(self.no), end='')
        else:
            self.tree.nodes[self.left].inorder()
            print(' {}'.format(self.no), end='')
            if self.right > -1:
                self.tree.nodes[self.right].inorder()

    def postorder(self):
        if not self.left > -1:
            print(' {}'.format(self.no), end='')
        else:
            self.tree.nodes[self.left].postorder()
            if self.right > -1:
                self.tree.nodes[self.right].postorder()
            print(' {}'.format(self.no), end='')


n = int(input())
ary = [[int(_) for _ in input().split()] for i in range(n)]
tree = Tree(ary)
tree.preorder()
tree.inorder()
tree.postorder()

Submission status: Wrong Answer

Solution code:
class NullNode():
    def __init__(self):
        self.id = -1

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

    def inorder(self, node_list, out_list=[]):
        pass

    def postorder(self, node_list, out_list=[]):
        pass

def preorder(node, out_list=[]):
    if node.id != -1:
        out_list.append(str(node.id))
        out_list = preorder(node.left, out_list)
        out_list = preorder(node.right, out_list)
    return out_list

def inorder(node, out_list=[]):
    if node.id != -1:
        out_list = inorder(node.left, out_list)
        out_list.append(str(node.id))
        out_list = inorder(node.right, out_list)
    return out_list

def postorder(node, out_list=[]):
    if node.id != -1:
        out_list = postorder(node.left, out_list)
        out_list = postorder(node.right, out_list)
        out_list.append(str(node.id))
    return out_list

n = int(input())
node_list = [Node(id) for id in range(n)]
for i in range(n):
    [id, left, right] = [int(j) for j in input().split()]
    i_node = node_list[id]
    if left != -1:
        i_node.left = node_list[left]
        node_list[left].parent = node_list[id]
    if right != -1:
        i_node.right = node_list[right]
        node_list[right].parent = node_list[id]

print('Preorder')
out_list = preorder(node_list[0])
print(' ' + ' '.join(out_list))

print('Inorder')
out_list = inorder(node_list[0])
print(' ' + ' '.join(out_list))

print('Postorder')
out_list = postorder(node_list[0])
print(' ' + ' '.join(out_list))

Submission status: Wrong Answer

Solution code:
n = int(input())
tree = [[] for i in range(n)]
for i in range(n):
    id, left, right = map(int, input().split())
    tree[id] = [left, right]

def preoder(id):
    if id == -1:
        return
    print(' ' + str(id), end='')
    preoder(tree[id][0])
    preoder(tree[id][1])

def inorder(id):
    if id == -1:
        return
    inorder(tree[id][0])
    print(' ' + str(id), end='')
    inorder(tree[id][1])

def postorder(id):
    if id == -1:
        return
    postorder(tree[id][0])
    postorder(tree[id][1])
    print(' ' + str(id), end='')

print('Preoder')
preoder(0)
print('')
print('Inorder')
inorder(0)
print('')
print('Postorder')
postorder(0)

Submission status: Wrong Answer

Solution code:
n = int(input())
tree = [[-1, -1, True] for i in range(n)]
for i in range(n):
    id, left, right = map(int, input().split())
    if left != -1:
        tree[id][0] = left
        tree[left][2] = False
    if right != -1:
        tree[id][1] = right
        tree[right][2] = False

def preoder(id):
    if id == -1:
        return
    print(' ' + str(id), end='')
    preoder(tree[id][0])
    preoder(tree[id][1])

def inorder(id):
    if id == -1:
        return
    inorder(tree[id][0])
    print(' ' + str(id), end='')
    inorder(tree[id][1])

def postorder(id):
    if id == -1:
        return
    postorder(tree[id][0])
    postorder(tree[id][1])
    print(' ' + str(id), end='')

for i, node in enumerate(tree):
    if node[2] == True:
        root = i

print('Preoder')
preoder(root)
print('')
print('Inorder')
inorder(root)
print('')
print('Postorder')
postorder(root)

Submission status: Wrong Answer

Solution code:
n = int(input())
tree = [[-1, -1, True] for i in range(n)]
for i in range(n):
    id, left, right = map(int, input().split())
    if left != -1:
        tree[id][0] = left
        tree[left][2] = False
    if right != -1:
        tree[id][1] = right
        tree[right][2] = False

def preoder(id):
    if id == -1:
        return
    print(' ' + str(id), end='')
    preoder(tree[id][0])
    preoder(tree[id][1])

def inorder(id):
    if id == -1:
        return
    inorder(tree[id][0])
    print(' ' + str(id), end='')
    inorder(tree[id][1])

def postorder(id):
    if id == -1:
        return
    postorder(tree[id][0])
    postorder(tree[id][1])
    print(' ' + str(id), end='')

root = 0
for i, node in enumerate(tree):
    if node[2] == True:
        root = i

print('Preoder')
preoder(root)
print('')
print('Inorder')
inorder(root)
print('')
print('Postorder')
postorder(root)

Submission status: Wrong Answer

Solution code:
#coding:utf-8
N = int(input())
T = [None for i in range(N)]
class Tree:
    def __init__(self, ID,p=-1):
        self.ID = ID

    def makeTree(self, tree):
        ID = tree.ID
        if ID == -1:
            return
        else:
            for i in range(N):
                if trees[i][0] == ID:
                    [ID,l,r] = trees[i]
                    tree.l = Tree(l)
                    tree.r = Tree(r)
                    treeL = tree.l
                    treeR = tree.r
                    treeL.p = tree
                    treeR.p = tree

                    self.makeTree(self,treeL)
                    self.makeTree(self,treeR)

def preParse(tree):
    ID = tree.ID
    if ID == -1:
        return
    else:
        global preList
        preList.append(ID)
        treeL = tree.l
        treeR = tree.r
        preParse(treeL)
        preParse(treeR)
        
def inParse(tree):
    ID = tree.ID
    if ID == -1:
        return
    else:
        global inList
        treeL = tree.l
        treeR = tree.r
        inParse(treeL)
        inList.append(ID)
        inParse(treeR)

def posParse(tree):
    ID = tree.ID
    if ID == -1:
        return
    else:
        global posList
        treeL = tree.l
        treeR = tree.r
        posParse(treeL)
        posParse(treeR)
        posList.append(ID)
        
    
trees = [list(map(int,input().split())) for i in range(N)]
ID = trees[0][0]
tree = Tree(ID)
Tree.makeTree(Tree,tree)

preList = []
inList = []
posList = []
preParse(tree)
inParse(tree)
posParse(tree)

def convert(List, order):
    a =  " " + " ".join([str(num) for num in List])
    print("{}".format(order))
    print(a)
convert(preList, "Preorder")
convert(inList, "Inorder")
convert(posList, "Postorder")

Submission status: Wrong Answer

Solution code:
Parent = 0
Lchild = 1
Rchild = 2

def childs(n):
    return node[n][Lchild:Rchild+1]

def preorder(n):
    if n == -1: return []
    c1, c2 = childs(n)
    return [n] + preorder(c1) + preorder(c2)

def inorder(n):
    if n == -1: return []
    c1, c2 = childs(n)
    return inorder(c1) + [n] +inorder(c2)

def postorder(n):
    if n == -1: return []
    c1, c2 = childs(n)
    return postorder(c1) + postorder(c2) + [n]

n = int(input())
node = [[-1, -1, -1] for i in range(n)]
for i in range(n):
    j, e1, e2 = map(int, raw_input().split())
    if e1 != -1:
        node[j][Lchild] = e1
        node[e1][Parent] = j
    if e2 != -1:
        node[j][Rchild] = e2
        node[e2][Parent] = j

print 'Preorder'
print ' ' + ' '.join(map(str, preorder(0)))

print 'Inorder'
print ' ' + ' '.join(map(str, inorder(0)))

print 'Postorder'
print ' ' + ' '.join(map(str, postorder(0)))

Submission status: Wrong Answer

Solution code:
Parent = 0
Lchild = 1
Rchild = 2

def childs(n):
    return node[n][Lchild:Rchild+1]

def preorder(n):
    if n == -1: return []
    c1, c2 = childs(n)
    return [n] + preorder(c1) + preorder(c2)

def inorder(n):
    if n == -1: return []
    c1, c2 = childs(n)
    return inorder(c1) + [n] +inorder(c2)

def postorder(n):
    if n == -1: return []
    c1, c2 = childs(n)
    return postorder(c1) + postorder(c2) + [n]

n = int(input())
node = [[-1, -1, -1] for i in range(n)]
for i in range(n):
    j, e1, e2 = map(int, raw_input().split())
    if e1 != -1:
        node[j][Lchild] = e1
        node[e1][Parent] = j
    if e2 != -1:
        node[j][Rchild] = e2
        node[e2][Parent] = j
for root in range(n):
    if node[i][Parent] == -1: break

print 'Preorder'
print ' ' + ' '.join(map(str, preorder(root)))

print 'Inorder'
print ' ' + ' '.join(map(str, inorder(root)))

print 'Postorder'
print ' ' + ' '.join(map(str, postorder(root)))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function
from sys import stdin


class Node(object):
    def __init__(self):
        self.id = None
        self.parent = -1
        self.childs = None


def preorder_walk(data, index, out):
    node = data[index]
    out.append(node.id)
    for cidx in node.childs:
        if cidx >= 0:
            preorder_walk(data, cidx, out)


def inorder_walk(data, index, out):
    node = data[index]
    for cidx in node.childs:
        if cidx >= 0:
            inorder_walk(data, cidx, out)
            if node.id not in out:
                out.append(node.id)
    if node.id not in out:
        out.append(node.id)


def postorder_wark(data, index, out):
    node = data[index]
    for cidx in node.childs:
        if cidx >= 0:
            postorder_wark(data, cidx, out)
    out.append(node.id)


n = int(stdin.readline())
#assert 1 <= n <= 25
data = [Node() for _ in range(n)]
for _ in range(n):
    idx, left, right = (int(s) for s in stdin.readline().split())
    data[idx].id = idx
    data[idx].childs = [left, right]
    for c in data[idx].childs:
        data[c].parent = idx

for name, func in (('Preorder', preorder_walk), ('Inoder', inorder_walk),
                   ('Postorder', postorder_wark)):
    out = []
    func(data, 0, out)
    print(name)
    print(*out)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function
from sys import stdin


class Node(object):
    def __init__(self):
        self.id = None
        self.parent = -1
        self.childs = None


def preorder_walk(data, index, out):
    node = data[index]
    out.append(node.id)
    for cidx in node.childs:
        if cidx >= 0:
            preorder_walk(data, cidx, out)


def inorder_walk(data, index, out):
    node = data[index]
    for cidx in node.childs:
        if cidx >= 0:
            inorder_walk(data, cidx, out)
            if node.id not in out:
                out.append(node.id)
    if node.id not in out:
        out.append(node.id)


def postorder_wark(data, index, out):
    node = data[index]
    for cidx in node.childs:
        if cidx >= 0:
            postorder_wark(data, cidx, out)
    out.append(node.id)


n = int(stdin.readline())
#assert 1 <= n <= 25
data = [Node() for _ in range(n)]
for _ in range(n):
    idx, left, right = (int(s) for s in stdin.readline().split())
    data[idx].id = idx
    data[idx].childs = [left, right]
    for c in data[idx].childs:
        data[c].parent = idx

for name, func in (('Preorder\n', preorder_walk),
                   ('Inorder\n', inorder_walk),
                   ('Postorder\n', postorder_wark)):
    out = []
    func(data, 0, out)
    print(name, *out)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function
from sys import stdin


class Node(object):
    def __init__(self):
        self.id = None
        self.parent = -1
        self.childs = None


def preorder_walk(data, index, out):
    node = data[index]
    out.append(node.id)
    for cidx in node.childs:
        if cidx >= 0:
            preorder_walk(data, cidx, out)


def inorder_walk(data, index, out):
    node = data[index]
    for cidx in node.childs:
        if cidx >= 0:
            inorder_walk(data, cidx, out)
            if node.id not in out:
                out.append(node.id)
    if node.id not in out:
        out.append(node.id)


def postorder_wark(data, index, out):
    node = data[index]
    for cidx in node.childs:
        if cidx >= 0:
            postorder_wark(data, cidx, out)
    out.append(node.id)


n = int(stdin.readline())
#assert 1 <= n <= 25
data = [Node() for _ in range(n)]
for _ in range(n):
    idx, left, right = (int(s) for s in stdin.readline().split())
    data[idx].id = idx
    data[idx].childs = [left, right]
    for c in data[idx].childs:
        if c >= 0:
            data[c].parent = idx

start = None
for node in data:
    if node.parent == -1:
        start = node.id
        break

for name, func in (('Preorder\n', preorder_walk),
                   ('Inorder\n', inorder_walk),
                   ('Postorder\n', postorder_wark)):
    out = []
    func(data, start, out)
    print(name, *out)

Submission status: Accepted

Solution code:
N = int(input())

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

T = [Node() for _ in range(N)]

for _ in range(N):
    id, left, right = map(int, input().split())

    T[id].left = left
    T[id].right = right

    if left != -1:
        T[left].parent = id
    if right != -1:
        T[right].parent = id


def preorder(id):
    preorder_list.append(id)

    if T[id].left != -1:
        preorder(T[id].left)
    if T[id].right != -1:
        preorder(T[id].right)

def inorder(id):
    left = T[id].left
    right = T[id].right

    if left != -1:
        inorder(T[id].left)
    inorder_list.append(id)

    if right != -1:
        inorder(right)

def get_right_sibling(id):
    parent_id = T[id].parent
    if parent_id == -1:
        return -1
    if T[parent_id].right != id:
        return T[parent_id].right

    return -1

def postorder(id):
    left = T[id].left
    right = T[id].right

    if left != -1:
        postorder(left)

    if right != -1:
        postorder(right)

    postorder_list.append(id)

preorder_list = []
inorder_list = []
postorder_list = []
for id in range(N):
    if T[id].parent == -1:
        preorder(id)
        inorder(id)
        postorder(id)
        break


print("Preorder")
print(" "+" ".join(map(str, preorder_list)))
print("Inorder")
print(" "+" ".join(map(str, inorder_list)))
print("Postorder")
print(" "+" ".join(map(str, postorder_list)))

Submission status: Accepted

Solution code:
N = int(input())

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

T = [Node() for _ in range(N)]

for _ in range(N):
    id, left, right = map(int, input().split())

    T[id].left = left
    T[id].right = right

    if left != -1:
        T[left].parent = id
    if right != -1:
        T[right].parent = id


def preorder(id):
    preorder_list.append(id)

    if T[id].left != -1:
        preorder(T[id].left)
    if T[id].right != -1:
        preorder(T[id].right)

def inorder(id):
    left = T[id].left
    right = T[id].right

    if left != -1:
        inorder(T[id].left)
    inorder_list.append(id)

    if right != -1:
        inorder(right)

def postorder(id):
    left = T[id].left
    right = T[id].right

    if left != -1:
        postorder(left)

    if right != -1:
        postorder(right)

    postorder_list.append(id)

preorder_list = []
inorder_list = []
postorder_list = []
for id in range(N):
    if T[id].parent == -1:
        preorder(id)
        inorder(id)
        postorder(id)
        break


print("Preorder")
print(" "+" ".join(map(str, preorder_list)))
print("Inorder")
print(" "+" ".join(map(str, inorder_list)))
print("Postorder")
print(" "+" ".join(map(str, postorder_list)))

Submission status: Accepted

Solution code:
N = int(input())

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

T = [Node() for _ in range(N)]

for _ in range(N):
    id, left, right = map(int, input().split())

    T[id].left = left
    T[id].right = right

    if left != -1:
        T[left].parent = id
    if right != -1:
        T[right].parent = id


def preorder(id):
    if id == -1:
        return

    preorder_list.append(id)

    preorder(T[id].left)
    preorder(T[id].right)

def inorder(id):
    if id == -1:
        return

    inorder(T[id].left)
    inorder_list.append(id)
    inorder(T[id].right)

def postorder(id):
    if id == -1:
        return

    postorder(T[id].left)
    postorder(T[id].right)
    postorder_list.append(id)

preorder_list = []
inorder_list = []
postorder_list = []
for id in range(N):
    if T[id].parent == -1:
        preorder(id)
        inorder(id)
        postorder(id)
        break


print("Preorder")
print(" "+" ".join(map(str, preorder_list)))
print("Inorder")
print(" "+" ".join(map(str, inorder_list)))
print("Postorder")
print(" "+" ".join(map(str, postorder_list)))