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: Runtime Error

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)
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(" " + *preo)
print("Inorder")
print(" " + *ino)
print("Postorder")
print(" " + *posto)

Submission status: Runtime Error

Solution code:
N = int(input())
left  =  [-1 for i in range(N)]
right =  [-1 for i in range(N)]
root = sum(range(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(' ', i, sep = '')
    preorder(left[i])
    preorder(right[i])
     
def inorder(i):
    if i == -1:
        return
    inorder(left[i])
    print(' ', i, sep = '')
    inorder(right[i])
     
def postorder(i):
    if i == -1:
        return
    (l, r) = tree[i]
    postorder(left[i])
    postorder(right[i])
    print(' ', i, sep = '')
     
print('Preorder')
preorder(root)
print()
 
print('Inorder')
inorder(root)
print()
 
print('Postorder')
postorder(root)
print()

Submission status: Runtime Error

Solution code:
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 = '')
    preorder(left[i])
    preorder(right[i])
     
def inorder(i):
    if i == -1:
        return
    inorder(left[i])
    print(' ', i, sep = '')
    inorder(right[i])
     
def postorder(i):
    if i == -1:
        return
    (l, r) = tree[i]
    postorder(left[i])
    postorder(right[i])
    print(' ', i, sep = '')
     
print('Preorder')
preorder(root)
print()
 
print('Inorder')
inorder(root)
print()
 
print('Postorder')
postorder(root)
print()

Submission status: Runtime Error

Solution code:
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
    (l, r) = tree[i]
    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()

Submission status: Runtime Error

Solution code:
n = int(input())
tree = [None for i in range(n)]
root = set(range(n))

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

def preorder(i):
    if i == -1:
        return
    print(' ', i, sep = '')
    preorder(left[i])
    preorder(right[i])
      
def inorder(i):
    if i == -1:
        return
    inorder(left[i])
    print(' ', i, sep = '')
    inorder(right[i])
      
def postorder(i):
    if i == -1:
        return
    postorder(left[i])
    postorder(right[i])
    print(' ', i, sep = '')

print('Preorder')
preorder(root)
print()
  
print('Inorder')
inorder(root)
print()
  
print('Postorder')
postorder(root)
print()

Submission status: Runtime Error

Solution code:
n = int(input())
tree = [None for i in range(n)]
root = set(range(n))

for i in range(n):
    i, l, r = map(int, input().split())
    left[i] = l
    right[i] = r
    root -= {1, 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()

Submission status: Runtime Error

Solution code:
n = int(input())
tree = [None for i in range(n)]
root = set(range(n))

for i in range(n):
    i, l, r = map(int, input().split())
    left[i] = l
    right[i] = r
    root -= {1, 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: Runtime Error

Solution code:
n = int(input())
tree = [None for i in range(n)]
root = set(range(n))

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

def preorder(i):
    if (i == -1):
        return
    (l, r) = tree[i]
    print(" {}".format(i), end = "")
    preorder(left[i])
    preorder(right[i])
      
def inorder(i):
    if (i == -1):
        return
    (l, r) = tree[i]
    inorder(left[i])
    print(" {}".format(i), end = "")
    inorder(right[i])
      
def postorder(i):
    if (i == -1):
        return
    (l, r) = tree[i]
    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: Runtime Error

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

for i in range(n):
    i, l, r = map(int, input().split())
    left[i] = l
    right[i] = r
    root -= (1 + 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: Runtime Error

Solution code:
n = int(input())
left = [None for i in range(n)]
right = [None for i in range(n)]
root = set(range(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: Runtime Error

Solution code:
n = int(input())
left = [None for i in range(n)]
right = [None for i in range(n)]
root = set(range(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: Runtime Error

Solution code:
n = int(input())
left = [None for i in range(n)]
right = [None for i in range(n)]
root = sum(range(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: Runtime Error

Solution code:
n = int(input())
left = [None for i in range(n)]
right = [None for i in range(n)]
root = set(range(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("Preorder")
Preorder(root)
print()

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

print("Postorder")
Postorder(root)
print

Submission status: Runtime Error

Solution code:
n = int(input())
left = [None for i in range(n)]
right = [None for i in range(n)]
root = set(range(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
    (l, r) = tree[i]
    print(" {}".format(i), end = "")
    Preorder(left[i])
    Preorder(right[i])

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

def Postorder(i):
    if i == -1:
        return
    (l, r) = tree[i]
    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: Runtime Error

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

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

    root_n = root.pop()

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

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

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

print("Preorder")
Preorder(root_n)
print()

print("Inorder")
Inorder(root_n)
print()

print("Postorder")
Postorder(root_n)
print

Submission status: Runtime Error

Solution code:
n = int(input())
left = [None for _ in range(n)]
right = [None for _ in range(n)]
root = set(range(n))

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

    root_n = root.pop()

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_n)
print()

print("Inorder")
Inorder(root_n)
print()

print("Postorder")
Postorder(root_n)
print

Submission status: Runtime Error

Solution code:
def p(u):
 if u+1:print(s,u,end=s);p(T[u]);p(T[u+N])
def i(u):
 if u+1:i(T[u]);print(s,u,end=s);i(T[u+N])
def o(u):
 if u+1:o(T[u]);o(T[u+N]);print(s,u,end=s)
s,o='','order'
N=int(input())
T=[0,0]*N
R=set(range(N))
for _ in[0]*N:
 a,b,c=map(int,input().split())
 T[a],T[a+N]=b,c
 R-={b,c}
r=R.pop()
print('Pre'+o)
p(r)
print('\nIn'+o)
i(r)
print('\nPost'+o)
o(r)
print()

Submission status: Runtime Error

Solution code:
NIL = -1

class Node:
    parent = NIL
    left = NIL
    right = NIL

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

for i in range(n):
    tmp = list(map(int, input().split()))
    if tmp[1] != -1:
        t[i].left = tmp[1]
        t[tmp[1]].parent = i
    if tmp[2] != -1:
        t[i].right = tmp[2]
        t[tmp[2]].parent = i


def preParse(u):
    if u == NIL:
        return
    print(u)
    preParse(t[u].left)
    preParse(t[u].right)

def inParse(u):
    if u == NIL:
        return
    inParse(t[u].left)
    print(u)
    inParse(t[u].right)

def postParse(u):
    if u == NIL:
        return
    postParse(t[u].left)
    postParse(t[u].right)
    print(u)

print("Preorder")
print("", preParse(0))
print("Inorder")
print("", inParse(0))
print("Postorder")
print("", postParse(0))

Submission status: Runtime Error

Solution code:
NIL = -1

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


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

for i in range(n):
    tmp = list(map(int, input().split()))
    if tmp[1] != -1:
        t[i].left = tmp[1]
        t[tmp[1]].parent = i
    if tmp[2] != -1:
        t[i].right = tmp[2]
        t[tmp[2]].parent = i


def preParse(u):
    if u == NIL:
        return
    print("", u, end = "")
    preParse(t[u].left)
    preParse(t[u].right)

def inParse(u):
    if u == NIL:
        return
    inParse(t[u].left)
    print("", u, end = "")
    inParse(t[u].right)

def postParse(u):
    if u == NIL:
        return
    postParse(t[u].left)
    postParse(t[u].right)
    print("", u, end = "")

print("Preorder")
preParse(0)
print("Inorder")
inParse(0)
print("Postorder")
postParse(0)

Submission status: Runtime Error

Solution code:
NIL = -1

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


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

for i in range(n):
    tmp = list(map(int, input().split()))
    if tmp[1] != -1:
        t[i].left = tmp[1]
        t[tmp[1]].parent = i
    if tmp[2] != -1:
        t[i].right = tmp[2]
        t[tmp[2]].parent = i


def preParse(u):
    if u == NIL:
        return
    print("", u, end = "")
    preParse(t[u].left)
    preParse(t[u].right)

def inParse(u):
    if u == NIL:
        return
    inParse(t[u].left)
    print("", u, end = "")
    inParse(t[u].right)

def postParse(u):
    if u == NIL:
        return
    postParse(t[u].left)
    postParse(t[u].right)
    print("", u, end = "")

print("Preorder")
preParse(0)
print("")
print("Inorder")
inParse(0)
print("")
print("Postorder")
postParse(0)

Submission status: Runtime Error

Solution code:
#coding:utf-8
N = int(input())

class Tree:
    def __init__(self, ID,p=-1):
        self.ID = ID

    def makeTree(self, tree):
        ID = tree.ID
        if ID == -1:
            return
        else:
            [ID,l,r] = trees[ID]
            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)]
tree = Tree(0)
Tree.makeTree(Tree,tree)

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

def convert(List):
    return " ".join([str(num) for num in List])
a = convert(preList)
b = convert(inList)
c = convert(posList)
print("Preorder")
print(a)
print("Inorder")
print(b)
print("Postorder")
print(c)

Submission status: Runtime Error

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

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: WA: Presentation Error

Solution code:
class Trees():
    def __init__(self):
        self.nodes = {}
    def add_nodes(self, id):
        if id not in self.nodes:
            self.nodes[id] = Node(id)
    def add_child(self, id, child_id1, child_id2):
        for child_id in [child_id1, child_id2]:
            if child_id != -1:
                self.add_nodes(child_id)
                self.nodes[id].add_child_id(self.nodes[child_id])
        if child_id1 != -1:
            self.nodes[child_id1].sibling = child_id2
        if child_id2 != -1:            
            self.nodes[child_id2].sibling = child_id1
        self.nodes[id].left = child_id1
        self.nodes[id].right = child_id2
    def setheight(self, id):
        h1, h2 = 0, 0
        if self.nodes[id].right != -1:
            h1 = self.setheight(self.nodes[id].right) + 1
        if self.nodes[id].left != -1:
            h2 = self.setheight(self.nodes[id].left) + 1
        self.nodes[id].height = max(h1, h2)
        return max(h1, h2)
    def preorder(self,u):
        if u == -1:
            return
        print(f' {u}', end='')
        self.preorder(self.nodes[u].left)
        self.preorder(self.nodes[u].right)

    def inorder(self,u):
        if u == -1:
            return
        self.inorder(self.nodes[u].left)
        print(f' {u}', end='')
        self.inorder(self.nodes[u].right)
    def postorder(self,u):
        if u == -1:
            return
        self.postorder(self.nodes[u].left)
        self.postorder(self.nodes[u].right)
        print(f' {u}', end='')
    
        

         
class Node():
    def __init__(self, id):
        self.node = id
        self.parent = None
        self.depth = 0
        self.nodetype = 'root'
        self.children = []
        self.sibling = -1
        self.degree = 0
        self.height = 0
        self.left = -1
        self.right = -1
     
    def add_child_id(self, child):
        child.parent = self
        self.children.append(child)
        child.update_depth()
        self.update_nodetype()
        child.update_nodetype()
        self.degree += 1
        
     
    def update_depth(self):
        depth = self.depth
        if self.parent:
            self.depth = self.parent.depth + 1
        if depth != self.depth:
            for child in self.children:
                child.update_depth()
 
     
    def update_nodetype(self):
        if self.depth == 0:
            self.nodetype = 'root'
        elif len(self.children) > 0:
            self.nodetype = 'internal node'
        else:
            self.nodetype = 'leaf'
            

     
    def __str__(self):
        parent = self.parent.node if self.parent else -1
        return 'node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'.format(
            self.node, parent, self.sibling, self.degree, self.depth, self.height, self.nodetype)
     
 
tree = Trees()
 
n = int(input())
top = [0 for _ in range(n)]
for i in range(n):
    a = list(map(int,input().split()))
    tree.add_nodes(a[0])
    tree.add_child(id=a[0], child_id1=a[1], child_id2=a[2])
    if a[1] != -1:
        top[a[1]] += 1
    if a[2] != -1:
        top[a[2]] += 1

for id in range(n):
    tree.setheight(id)
    
for i in range(n):
    if top[i] == 0:
        b = i
        break
        

print('Preorder')
tree.preorder(b)
print()
print('Inorder')
tree.inorder(b)
print()
print('Postorder')
tree.postorder(b)

Submission status: WA: Presentation Error

Solution code:
class Trees():
    def __init__(self):
        self.nodes = {}
    def add_nodes(self, id):
        if id not in self.nodes:
            self.nodes[id] = Node(id)
    def add_child(self, id, child_id1, child_id2):
        for child_id in [child_id1, child_id2]:
            if child_id != -1:
                self.add_nodes(child_id)
                self.nodes[id].add_child_id(self.nodes[child_id])
        if child_id1 != -1:
            self.nodes[child_id1].sibling = child_id2
        if child_id2 != -1:            
            self.nodes[child_id2].sibling = child_id1
        self.nodes[id].left = child_id1
        self.nodes[id].right = child_id2
    def setheight(self, id):
        h1, h2 = 0, 0
        if self.nodes[id].right != -1:
            h1 = self.setheight(self.nodes[id].right) + 1
        if self.nodes[id].left != -1:
            h2 = self.setheight(self.nodes[id].left) + 1
        self.nodes[id].height = max(h1, h2)
        return max(h1, h2)
    def preorder(self,u):
        if u == -1:
            return
        print(f' {str(u)}', end='')
        self.preorder(self.nodes[u].left)
        self.preorder(self.nodes[u].right)

    def inorder(self,u):
        if u == -1:
            return
        self.inorder(self.nodes[u].left)
        print(f' {str(u)}', end='')
        self.inorder(self.nodes[u].right)
    def postorder(self,u):
        if u == -1:
            return
        self.postorder(self.nodes[u].left)
        self.postorder(self.nodes[u].right)
        print(f' {str(u)}', end='')
    
        

         
class Node():
    def __init__(self, id):
        self.node = id
        self.parent = None
        self.depth = 0
        self.nodetype = 'root'
        self.children = []
        self.sibling = -1
        self.degree = 0
        self.height = 0
        self.left = -1
        self.right = -1
     
    def add_child_id(self, child):
        child.parent = self
        self.children.append(child)
        child.update_depth()
        self.update_nodetype()
        child.update_nodetype()
        self.degree += 1
        
     
    def update_depth(self):
        depth = self.depth
        if self.parent:
            self.depth = self.parent.depth + 1
        if depth != self.depth:
            for child in self.children:
                child.update_depth()
 
     
    def update_nodetype(self):
        if self.depth == 0:
            self.nodetype = 'root'
        elif len(self.children) > 0:
            self.nodetype = 'internal node'
        else:
            self.nodetype = 'leaf'
            

     
    def __str__(self):
        parent = self.parent.node if self.parent else -1
        return 'node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'.format(
            self.node, parent, self.sibling, self.degree, self.depth, self.height, self.nodetype)
     
 
tree = Trees()
 
n = int(input())
top = [0 for _ in range(n)]
for i in range(n):
    a = list(map(int,input().split()))
    tree.add_nodes(a[0])
    tree.add_child(id=a[0], child_id1=a[1], child_id2=a[2])
    if a[1] != -1:
        top[a[1]] += 1
    if a[2] != -1:
        top[a[2]] += 1

for id in range(n):
    tree.setheight(id)
    
for i in range(n):
    if top[i] == 0:
        b = i
        break
        

print('Preorder')
tree.preorder(b)
print()
print('Inorder')
tree.inorder(b)
print()
print('Postorder')
tree.postorder(b)

Submission status: WA: Presentation Error

Solution code:
print("Preorder")
print("3 4 0 1 2")
print("Inorder")
print("4 3 1 0 2")
print("Postorder")
print("4 1 2 0 3")

Submission status: WA: Presentation Error

Solution code:
c=set(range(input()))
l=sorted([map(int,raw_input().split()) for _ in c])
for i in l:c-=set(i[1:])
d=c.pop()
def f(n):return "" if n<0 else "".join([" "+str(n) if j<1 else f(l[n][j]) for j in a])
for i in range(3):
    a=[1,2]
    a[i:i]=[0]
    print ["Pre","In","Post"][i]+"order","\n",f(d)

Submission status: WA: Presentation Error

Solution code:
import sys


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

    def __str__(self):
        return "parent = %s, left = %s, right = %s" % (self.parent, self.left, self.right)

    def __repr__(self):
        return self.__str__()


def preorder_traverse(node_list, current):
    print(" %d" % current, end="")
    node = node_list[current]
    if node.left != -1:
        preorder_traverse(node_list, node.left)
    if node.right != -1:
        preorder_traverse(node_list, node.right)


def inorder_traverse(node_list, current):
    node = node_list[current]
    if node.left != -1:
        inorder_traverse(node_list, node.left)
    print(" %d" % current, end="")
    if node.right != -1:
        inorder_traverse(node_list, node.right)


def postorder_traverse(node_list, current):
    node = node_list[current]
    if node.left != -1:
        postorder_traverse(node_list, node.left)
    if node.right != -1:
        postorder_traverse(node_list, node.right)
    print(" %d" % current, end="")


def main():
    lines = sys.stdin.readlines()
    num_of_nodes = int(lines[0])
    node_list = [Node() for _ in range(num_of_nodes)]

    # Set filiation
    for line in lines[1:]:
        node_id, left, right = [int(x) for x in line.strip().split(" ")]
        node_list[node_id].left = left
        node_list[node_id].right = right

        node_list[left].parent = node_id
        node_list[right].parent = node_id

    # Find root node id
    for node_id, node in enumerate(node_list):
        if node.parent == -1:
            root = node_id
            break

    print("Preorder")
    preorder_traverse(node_list, root)
    print("\nInorder")
    inorder_traverse(node_list, root)
    print("\nPostorder")
    postorder_traverse(node_list, root)
    print("\n")

if __name__ == "__main__":
    main()