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

Solution code:
class Node:
    def __init__(self, id):
        self.id = id
        self.left = None
        self.right = None
        self.sibling = None
        self.parent = None

def preorder_tree_walk(root):
    result = []
    result.append(root.id)
    if root.left != None:
        result.extend(preorder_tree_walk(root.left))
    if root.right != None:
        result.extend(preorder_tree_walk(root.right))
    return result

def inorder_tree_walk(root):
    result = []
    if root.left != None:
        result.extend(inorder_tree_walk(root.left))
    result.append(root.id)
    if root.right != None:
        result.extend(inorder_tree_walk(root.right))
    return result

def postorder_tree_walk(root):
    result = []
    if root.left != None:
        result.extend(postorder_tree_walk(root.left))
    if root.right != None:
        result.extend(postorder_tree_walk(root.right))
    result.append(root.id)
    return result

n = int(raw_input())
tree = [Node(i) for i in xrange(n)]
for i in xrange(n):
    line = map(int, raw_input().split())
    id, left_id, right_id = line[0], line[1], line[2]
    if left_id != -1:
        tree[id].left = tree[left_id]
        tree[left_id].parent = tree[id]
    if right_id != -1:
        tree[id].right = tree[right_id]
        tree[right_id].parent = tree[id]
    if left_id != -1 and right_id != -1:
        tree[left_id].sibling = tree[right_id]
        tree[right_id].sibling = tree[left_id]

# find root
root = None
for t in tree:
    if t.parent == None:
        root = t

print 'Preorder'
print ' '.join(map(str, preorder_tree_walk(root)))
print 'Inorder'
print ' '.join(map(str, inorder_tree_walk(root)))
print 'Postorder'
print ' '.join(map(str, postorder_tree_walk(root)))

Submission status: WA: Presentation Error

Solution code:
class Node:
    def __init__(self,p,l,r):
        self.parent = p
        self.left = l
        self.right = r

def preorder(u):
    print u,
    if tree[u].left != -1:
        preorder(tree[u].left)
    if tree[u].right != -1:
        preorder(tree[u].right)

def inorder(u):
    if tree[u].left != -1:
        inorder(tree[u].left)
    print u,
    if tree[u].right != -1:
        inorder(tree[u].right)

def postorder(u):
    if tree[u].left != -1:
        postorder(tree[u].left)
    if tree[u].right != -1:
        postorder(tree[u].right)
    print u,



n = int(raw_input().strip())
tree = {}
for i in range(n):
    nid, left, right = map(int, raw_input().strip().split(' '))
    if not nid in tree: tree[nid] = Node(-1,left,right)
    else:
        tree[nid].left = left
        tree[nid].right = right
    if not left == -1:
        if not left in tree: tree[left] = Node(nid,-1,-1)
        else: tree[left].parent = nid
    if not right == -1:
        if not right in tree: tree[right] = Node(nid,-1,-1)
        else: tree[right].parent = nid

r = -1
for i in range(len(tree)):
    if tree[i].parent == -1:
        r = i
        break


print "Preorder"
preorder(r)
print
print "Inorder"
inorder(r)
print
print "Postorder"
postorder(r)
print

Submission status: WA: Presentation Error

Solution code:
n = int(raw_input())



FORMAT = ('node {0.id}: parent = {0.parent}, sibling = {0.sibling}, degree = {0.degree}, depth = {0.depth}, height = {0.height}, {0.type}').format

class Node:
    def __init__(self):
        self.id = -1
        self.parent = -1
        self.left = -1
        self.right = -1
        self.sibling = -1
        self.degree = 0
        self.depth = 0
        self.height = 0
        self.type = 'leaf' if self.height == 0 else 'internal node'
        
    def setType(self):
        if self.height == 0 and self.parent != -1:
            self.type = 'leaf'
        elif self.parent == -1:
            self.type = 'root'
        else:
            self.type = 'internal node'

    def __str__(self):
        return FORMAT(self)

def preParse(u):
    if u == -1:
        return
    print u,
    preParse(T[u].left)
    preParse(T[u].right)

def inParse(u):
    if u == -1:
        return
    inParse(T[u].left)
    print u,
    inParse(T[u].right)

def postParse(u):
    if u == -1:
        return
    postParse(T[u].left)
    postParse(T[u].right)
    print u,


T = [Node() for _ in xrange(n)]

for i in xrange(n):
    a = map(int, raw_input().split())
    u = a[0]
    l = a[1]
    r = a[2]
    T[u].id = u
    T[u].left = l  #set child
    T[u].right = r  #set child
    if l != -1 and r != -1:
        T[l].parent = u  #set parent
        T[r].parent = u  #set parent
    elif l != -1 and r == -1:
        T[l].parent = u  #set parent
    elif l == -1 and r != -1:
        T[r].parent = u  #set parent

    if l != -1 and r != -1:
        T[u].degree = 2
        T[l].sibling = r
        T[r].sibling = l
    elif l != -1 and r == -1:
        T[u].degree = 1
    elif  l == -1 and r != -1:
        T[u].degree = 1

N = 0
for i in xrange(n):
    if T[i].parent == -1:
        N = T[i].id

print 'Preorder'
print '',
preParse(N)
print ''
print 'Inorder'
print '',
inParse(N)
print ''
print 'Postorder'
print '',
postParse(N)

Submission status: WA: Presentation Error

Solution code:
n = int(raw_input())



FORMAT = ('node {0.id}: parent = {0.parent}, sibling = {0.sibling}, degree = {0.degree}, depth = {0.depth}, height = {0.height}, {0.type}').format

class Node:
    def __init__(self):
        self.id = -1
        self.parent = -1
        self.left = -1
        self.right = -1
        self.sibling = -1
        self.degree = 0
        self.depth = 0
        self.height = 0
        self.type = 'leaf' if self.height == 0 else 'internal node'
        
    def setType(self):
        if self.height == 0 and self.parent != -1:
            self.type = 'leaf'
        elif self.parent == -1:
            self.type = 'root'
        else:
            self.type = 'internal node'

    def __str__(self):
        return FORMAT(self)

def preParse(u):
    if u == -1:
        return
    print u,
    preParse(T[u].left)
    preParse(T[u].right)

def inParse(u):
    if u == -1:
        return
    inParse(T[u].left)
    print u,
    inParse(T[u].right)

def postParse(u):
    if u == -1:
        return
    postParse(T[u].left)
    postParse(T[u].right)
    print u,


T = [Node() for _ in xrange(n)]

for i in xrange(n):
    a = map(int, raw_input().split())
    u = a[0]
    l = a[1]
    r = a[2]
    T[u].id = u
    T[u].left = l  #set child
    T[u].right = r  #set child
    if l != -1 and r != -1:
        T[l].parent = u  #set parent
        T[r].parent = u  #set parent
    elif l != -1 and r == -1:
        T[l].parent = u  #set parent
    elif l == -1 and r != -1:
        T[r].parent = u  #set parent

    if l != -1 and r != -1:
        T[u].degree = 2
        T[l].sibling = r
        T[r].sibling = l
    elif l != -1 and r == -1:
        T[u].degree = 1
    elif  l == -1 and r != -1:
        T[u].degree = 1

N = 0
for i in xrange(n):
    if T[i].parent == -1:
        N = T[i].id

print 'Preorder'
print '',
preParse(N)
print ''
print 'Inorder'
print '',
inParse(N)
print ''
print 'Postorder'
print '',
postParse(N)
print ''

Submission status: WA: Presentation Error

Solution code:
from collections import namedtuple

class TreeWalk:
    def __init__(self, t):
        self.t = t

    def preParse(self, u):
        if u == -1:
            return 
        print(" ", str(u), end = "")
        self.preParse(self.t[u].l)
        self.preParse(self.t[u].r)

    def inParse(self, u):
        if u == -1:
            return 
        self.inParse(self.t[u].l)
        print(" ", str(u), end = "")
        self.inParse(self.t[u].r)

    def postParse(self, u):
        if u == -1:
            return 
        self.postParse(self.t[u].l)
        self.postParse(self.t[u].r)
        print(" ", str(u), end = "")
    
if __name__ == '__main__':
    n = int(input().rstrip())
    Node = namedtuple('Node', ['p', 'l', 'r'])
    t = [Node(-1, -1, -1)] * n
    root = -1
    for i in range(n):
        v, l, r = [int(i) for i in input().rstrip().split(" ")]
        t[v] = t[v]._replace(l = l, r = r)
        if l != -1:
            t[l] = t[l]._replace(p = v)
        if r != -1:
            t[r] = t[r]._replace(p = v)
    for i in range(n):
        if (t[i].p == -1):
            root = i

    x = TreeWalk(t)
    print("Preorder")
    x.preParse(root)
    print()
    print("Inorder")
    x.inParse(root)
    print()
    print("Postorder")
    x.postParse(root)
    print()

Submission status: WA: Presentation Error

Solution code:
from collections import namedtuple

class TreeWalk:
    def __init__(self, t):
        self.t = t

    def preParse(self, u):
        if u == -1:
            return 
        print(" ", str(u), end = "")
        self.preParse(self.t[u].l)
        self.preParse(self.t[u].r)

    def inParse(self, u):
        if u == -1:
            return 
        self.inParse(self.t[u].l)
        print(" ", str(u), end = "")
        self.inParse(self.t[u].r)

    def postParse(self, u):
        if u == -1:
            return 
        self.postParse(self.t[u].l)
        self.postParse(self.t[u].r)
        print(" ", str(u), end = "")
    
if __name__ == '__main__':
    n = int(input().rstrip())
    Node = namedtuple('Node', ['p', 'l', 'r'])
    t = [Node(-1, -1, -1)] * n
    root = -1
    for i in range(n):
        v, l, r = [int(i) for i in input().rstrip().split(" ")]
        t[v] = t[v]._replace(l = l, r = r)
        if l != -1:
            t[l] = t[l]._replace(p = v)
        if r != -1:
            t[r] = t[r]._replace(p = v)
    for i in range(n):
        if (t[i].p == -1):
            root = i

    x = TreeWalk(t)
    print("Preorder")
    x.preParse(root)
    print()
    print("Inorder")
    x.inParse(root)
    print()
    print("Postorder")
    x.postParse(root)

Submission status: WA: Presentation Error

Solution code:
import sys

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

    def preorderTreeWalk(self):
        if self.id == -1:
            return
        print self.id,
        self.left.preorderTreeWalk()
        self.right.preorderTreeWalk()

    def inorderTreeWalk(self):
        if self.id == -1:
            return
        self.left.inorderTreeWalk()
        print self.id,
        self.right.inorderTreeWalk()

    def postorderTreeWalk(self):
        if self.id == -1:
            return
        self.left.postorderTreeWalk()
        self.right.postorderTreeWalk()
        print self.id,

    def printTree(self):
        print self.id,
        if self.left.id != -1:
            self.left.printTree()
        if self.right.id != -1:
            self.right.printTree()

def buildTree(id, nodeList):
    leftId, rightId = nodeList[id][0], nodeList[id][1]
    dummy = Node(-1, None, None)

    if leftId == -1 and rightId == -1:
        return Node(id, dummy, dummy)

    if leftId == -1:
        left = dummy
    else:
        left = buildTree(leftId, nodeList)

    if rightId == -1:
        right = dummy
    else:
        right = buildTree(rightId, nodeList)

    node = Node(id, left, right)
    node.left.parent = node
    node.right.parent = node

    return node

if __name__ == "__main__":
    lines = sys.stdin.readlines()
    N = int(lines[0])
    del lines[0]

    nodeList = [[]] * N
    sum = N * (N - 1) / 2
    for line in lines:
        line = map(int, line.split())
        id, children = line[0], line[1:]
        nodeList[id] = children
        for child in children:
            if child == -1:
                continue
            sum -= child

    root = buildTree(sum, nodeList)
    root.parent = Node(-1, None, None)

    print "Preorder"
    root.preorderTreeWalk()
    print ""

    print "Inorder"
    root.inorderTreeWalk()
    print ""

    print "Postorder"
    root.postorderTreeWalk()
    print ""

Submission status: WA: Presentation Error

Solution code:
import sys

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

    def preorderTreeWalk(self):
        if self.id == -1:
            return []
        return [self.id] + self.left.preorderTreeWalk() + self.right.preorderTreeWalk()

    def inorderTreeWalk(self):
        if self.id == -1:
            return []
        return self.left.inorderTreeWalk() + [self.id] + self.right.inorderTreeWalk()

    def postorderTreeWalk(self):
        if self.id == -1:
            return []
        return self.left.postorderTreeWalk() + self.right.postorderTreeWalk() + [self.id]

def buildTree(id, nodeList):
    leftId, rightId = nodeList[id][0], nodeList[id][1]
    dummy = Node(-1, None, None)

    if leftId == -1 and rightId == -1:
        return Node(id, dummy, dummy)

    if leftId == -1:
        left = dummy
    else:
        left = buildTree(leftId, nodeList)

    if rightId == -1:
        right = dummy
    else:
        right = buildTree(rightId, nodeList)

    node = Node(id, left, right)
    node.left.parent = node
    node.right.parent = node

    return node

if __name__ == "__main__":
    lines = sys.stdin.readlines()
    N = int(lines[0])
    del lines[0]

    nodeList = [[]] * N
    sum = N * (N - 1) / 2
    for line in lines:
        line = map(int, line.split())
        id, children = line[0], line[1:]
        nodeList[id] = children
        for child in children:
            if child == -1:
                continue
            sum -= child

    root = buildTree(sum, nodeList)
    root.parent = Node(-1, None, None)

    print "Preorder"
    order = root.preorderTreeWalk()
    print " ".join(map(str, order))

    print "Inorder"
    order = root.inorderTreeWalk()
    print " ".join(map(str, order))

    print "Postorder"
    order = root.postorderTreeWalk()
    print " ".join(map(str, order))

Submission status: WA: Presentation Error

Solution code:
#coding:UTF-8
def isRoot(point,A,n):
    for i in range(n):
        if A[i][1]==point or A[i][2]==point:
            return False
    return True

def isBranch(point,A,ans):
    if A[point][1]!=-1:
        ans.append(A[point][1])
        isBranch(A[point][1],A,ans)
    if A[point][2]!=-1:
        ans.append(A[point][2])
        isBranch(A[point][2],A,ans)
        
def isIn(point,A,ans):
    if A[point][1]!=-1:
        isIn(A[point][1],A,ans)
    ans.append(point)
    if A[point][2]!=-1:
        isIn(A[point][2],A,ans)

def isPost(point,A,ans):
    if A[point][1]!=-1:
        isPost(A[point][1],A,ans)
    if A[point][2]!=-1:
        isPost(A[point][2],A,ans)
    ans.append(point)
        
def Pre(A,n):
    ans=[]
    for i in range(n):
        if isRoot(A[i][0],A,n)==True:
            ans.append(A[i][0])
            if A[i][1]!=-1:
                ans.append(A[i][1])
                isBranch(A[i][1],A,ans)
            if A[i][2]!=-1:
                ans.append(A[i][2])
                isBranch(A[i][2],A,ans)
    print("Preorder")
    for i in range(n):
        ans[i]=str(ans[i])
    print(" ".join(ans))

def In(A,n):
    ans=[]
    for i in range(n):
        if isRoot(A[i][0],A,n)==True:
            if A[i][1]!=-1:
                isIn(A[i][1],A,ans)
            ans.append(A[i][0])
            if A[i][2]!=-1:
                isIn(A[i][2],A,ans)
    print("Inorder")
    for i in range(n):
        ans[i]=str(ans[i])
    print(" ".join(ans))

def Post(A,n):
    ans=[]
    for i in range(n):
        if isRoot(A[i][0],A,n)==True:
            if A[i][1]!=-1:
                isPost(A[i][1],A,ans)
            if A[i][2]!=-1:
                isPost(A[i][2],A,ans)
            ans.append(A[i][0])
    print("Postorder")
    for i in range(n):
        ans[i]=str(ans[i])
    print(" ".join(ans))
    
def TW(A,n):
    Pre(A,n)
    In(A,n)
    Post(A,n)


if __name__=="__main__":
    n=int(input())
    A=[]
    for i in range(n):
        A.append(list(map(int,input().split(" "))))
    for i in range(n):
        minj=i
        for j in range(i,n):
            if A[j][0]<A[minj][0]:
                minj=j
        A[i],A[minj]=A[minj],A[i]
    TW(A,n)

Submission status: WA: Presentation Error

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

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)

Submission status: WA: Presentation Error

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
    if node == -1:
        return None
    print(node, end = " ")
    pre_order(node_list[node].left)
    pre_order(node_list[node].right)

def in_order(node):
    global node_list
    if node == -1:
        return None
    in_order(node_list[node].left)
    print(node, end = " ")
    in_order(node_list[node].right)

def post_order(node):
    global node_list
    if node == -1:
        return None
    post_order(node_list[node].left)
    post_order(node_list[node].right)
    print(node, end = " ")

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

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))

print("Preorder")
pre_order(root_node)
print("\nInorder")
in_order(root_node)
print("\nPostorder")
post_order(root_node)
print()

Submission status: WA: Presentation Error

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)