Problem:


Tree Walk

Binary trees are defined recursively. A binary tree T is a structure defined on a finite set of nodes that either

contains no nodes, or

is composed of three disjoint sets of nodes:

- a root node.

- a binary tree called its left subtree.

- a binary tree called its right subtree.

Your task is to write a program which perform tree walks (systematically traverse all nodes in a tree) based on the following algorithms:

Print the root, the left subtree and right subtree (preorder).

Print the left subtree, the root and right subtree (inorder).

Print the left subtree, right subtree and the root (postorder).

Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n-1.

Input

The first line of the input includes an integer n, the number of nodes of the tree.

In the next n linen, the information of each node is given in the following format:

id left right

id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1

Output

In the 1st line, print "Preorder", and in the 2nd line print a list of node IDs obtained by the preorder tree walk.

In the 3rd line, print "Inorder", and in the 4th line print a list of node IDs obtained by the inorder tree walk.

In the 5th line, print "Postorder", and in the 6th line print a list of node IDs obtained by the postorder tree walk.

Print a space character before each node ID.

Constraints

1 ≤ n ≤ 25

Sample Input 1

9
0 1 4
1 2 3
2 -1 -1
3 -1 -1
4 5 8
5 6 7
6 -1 -1
7 -1 -1
8 -1 -1

Sample Output 1

Preorder
 0 1 2 3 4 5 6 7 8
Inorder
 2 1 3 0 6 5 7 4 8
Postorder
 2 3 1 6 7 5 8 4 0

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.



Sample input:
9
0 1 4
1 2 3
2 -1 -1
3 -1 -1
4 5 8
5 6 7
6 -1 -1
7 -1 -1
8 -1 -1


Sample output:
Preorder
 0 1 2 3 4 5 6 7 8
Inorder
 2 1 3 0 6 5 7 4 8
Postorder
 2 3 1 6 7 5 8 4 0

Submission status: Accepted

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

Solution code:
class BinaryTree:
    class Node:
        def __init__(self, num, left_child, right_child):
            self.id = num
            self.left_child = left_child
            self.right_child = right_child
            
    def __init__(self, n):
        self.nodes = [None] * n
        self.root_id = int(n * (n - 1) / 2)

    def add_node(self, i_s):
        num, left_child, right_child = map(int, i_s.split())
        self.nodes[num] = BinaryTree.Node(num, left_child, right_child)
        if left_child != -1:
            self.root_id -= left_child
        if right_child != -1:
            self.root_id -= right_child

    def preorder_walk(self):
        print('Preorder')
        root_node = self.nodes[self.root_id]
        def _pre_walk(node):
            print(' {0}'.format(node.id), end = '')
            if node.left_child != -1:
                _pre_walk(self.nodes[node.left_child])
            if node.right_child != -1:
                _pre_walk(self.nodes[node.right_child])
        _pre_walk(root_node)
        print('')

    def inorder_walk(self):
        print('Inorder')
        root_node = self.nodes[self.root_id]
        def _in_walk(node):
            if node.left_child != -1:
                _in_walk(self.nodes[node.left_child])
            print(' {0}'.format(node.id), end = '')
            if node.right_child != -1:
                _in_walk(self.nodes[node.right_child])
        _in_walk(root_node)
        print('')

    def postorder_walk(self):
        print('Postorder')
        root_node = self.nodes[self.root_id]
        def _post_walk(node):
            if node.left_child != -1:
                _post_walk(self.nodes[node.left_child])
            if node.right_child != -1:
                _post_walk(self.nodes[node.right_child])
            print(' {0}'.format(node.id), end = '')
        _post_walk(root_node)
        print('')


n = int(input())

BT = BinaryTree(n)

for i in range(n):
    BT.add_node(input())

BT.preorder_walk()
BT.inorder_walk()
BT.postorder_walk()

Submission status: Accepted

Solution code:
class BinaryTree:
    class Node:
        def __init__(self, num, left_child, right_child):
            self.id = num
            self.left_child = left_child
            self.right_child = right_child
            
    def __init__(self, n):
        self.nodes = [None] * n
        self.root_id = int(n * (n - 1) / 2)

    def add_node(self, i_s):
        num, left_child, right_child = map(int, i_s.split())
        self.nodes[num] = BinaryTree.Node(num, left_child, right_child)
        if left_child != -1:
            self.root_id -= left_child
        if right_child != -1:
            self.root_id -= right_child

    def preorder_walk(self):
        print('Preorder')
        def _pre_walk(node_id):
            if node_id != -1:
                print(' {0}'.format(node_id), end = '')
                _pre_walk(self.nodes[node_id].left_child)
                _pre_walk(self.nodes[node_id].right_child)
        _pre_walk(self.root_id)
        print('')

    def inorder_walk(self):
        print('Inorder')
        root_node = self.nodes[self.root_id]
        def _in_walk(node_id):
            if node_id != -1:
                _in_walk(self.nodes[node_id].left_child)
                print(' {0}'.format(node_id), end = '')
                _in_walk(self.nodes[node_id].right_child)
        _in_walk(self.root_id)
        print('')

    def postorder_walk(self):
        print('Postorder')
        root_node = self.nodes[self.root_id]
        def _post_walk(node_id):
            if node_id != -1:
                _post_walk(self.nodes[node_id].left_child)
                _post_walk(self.nodes[node_id].right_child)
                print(' {0}'.format(node_id), end = '')
        _post_walk(self.root_id)
        print('')


n = int(input())

BT = BinaryTree(n)

for i in range(n):
    BT.add_node(input())

BT.preorder_walk()
BT.inorder_walk()
BT.postorder_walk()

Submission status: Accepted

Solution code:
class BinTree():
    def __init__(self):
        self.parent = -1
        self.left, self.right = -1, -1
        self.sib = -1
        self.dep, self.deg, self.h = 0, 0, 0
        self.state = "internal node"

    def set_node(self, nid, l, r):
        global root
        root -= {l, r}
        self.left, self.right = l, r
        self.deg = (l != -1) + (r != -1)
        if l != -1:
            left = trees[l]
            left.parent = nid
            left.sib = r
        if r != -1:
            right = trees[r]
            right.parent = nid
            right.sib = l

    def set_param(self):
        if self.parent != -1:
            self.dep = trees[self.parent].dep + 1
        if self.deg == 0:
            self.state = "leaf"
        if self.left != -1:
            left = trees[self.left]
            left.set_param()
            self.h = left.h + 1
        if self.right != -1:
            right = trees[self.right]
            right.set_param()
            if self.h <= right.h:
                self.h = right.h + 1
        if self.parent == -1:
            self.state = "root"

def pre_walk(nid):
    tree = trees[nid]
    print(" {}".format(nid), end="")
    if tree.left != -1:
        pre_walk(tree.left)
    if tree.right != -1:
        pre_walk(tree.right)

def preoder(root):
    print("Preorder")
    pre_walk(root)
    print()

def in_walk(nid):
    tree = trees[nid]
    if tree.left != -1:
        in_walk(tree.left)
    print(" {}".format(nid), end="")
    if tree.right != -1:
        in_walk(tree.right)

def inorder(root):
    print("Inorder")
    in_walk(root)
    print()

def post_walk(nid):
    tree = trees[nid]
    if tree.left != -1:
        post_walk(tree.left)
    if tree.right != -1:
        post_walk(tree.right)
    print(" {}".format(nid), end="")

def postorder(root):
    print("Postorder")
    post_walk(root)
    print()

n = int(input())
trees = [BinTree() for _ in range(n)]
root = set(range(n))
for _ in range(n):
    inp = list(map(int, input().split()))
    trees[inp[0]].set_node(*inp)
root = root.pop()
trees[root].set_param()
preoder(root)
inorder(root)
postorder(root)

Submission status: Accepted

Solution code:
#coding:utf-8
#1_7_C
def preorder(i):
    if i == -1:
        return
    (l, r) = tree[i]
    print(" {}".format(i), end = "")
    preorder(l)
    preorder(r)

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

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

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())
    tree[i] = (l, r)
    root -= set([l, r])

root_node = root.pop()

print("Preorder")
preorder(root_node)
print()

print("Inorder")
inorder(root_node)
print()

print("Postorder")
postorder(root_node)
print()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

def pre_order(id, list):
    if id > -1:
        list.append(id)
        pre_order(node_dic[id].left, list)
        pre_order(node_dic[id].right, list)

def in_order(id, list):
    if id > -1:
        in_order(node_dic[id].left, list)
        list.append(id)
        in_order(node_dic[id].right, list)

def post_order(id, list):
    if id > -1:
        post_order(node_dic[id].left, list)
        post_order(node_dic[id].right, list)
        list.append(id)

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

n = int(raw_input())
node_dic = {}
root = 0
for i in range(n):
    id, left, right = map(int, raw_input().split())
    node_dic[id] = Node_Class(left, right)
    root += i
for i in range(n):
    left = node_dic[i].left
    right = node_dic[i].right
    if left > -1:
        root -= left
    if right > -1:
        root -= right
A = []
B = []
C = []
pre_order(root, A)
in_order(root, B)
post_order(root, C)
print "Preorder"
print " "+" ".join(map(str, A))
print "Inorder"
print " "+" ".join(map(str, B))
print "Postorder"
print " "+" ".join(map(str, C))

Submission status: Accepted

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: Accepted

Solution code:
import sys

class Node:
    def __init__(self):
        pass

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

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

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

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

    tree = []
    for i in range(N):
        tree.append(Node())

    root = N * (N - 1) / 2
    for line in lines:
        info = map(int, line.split())
        id = info[0]
        tree[id].id = id
        tree[id].left = info[1]
        tree[id].right = info[2]
        if info[1] != -1:
            root -= info[1]
        if info[2] != -1:
            root -= info[2]

    print "Preorder"
    print "",
    preorderTreeWalk(root, tree)
    print

    print "Inorder"
    print "",
    inorderTreeWalk(root, tree)
    print

    print "Postorder"
    print "",
    postorderTreeWalk(root, tree)
    print

Submission status: Accepted

Solution code:
from collections import namedtuple
Node = namedtuple('Node', ['parent', 'children'])
  
class my_binary_tree:
    def __init__(self, N=[]):
        self.T = {}
        for ni in N: self.addNode(ni)
  
    def addNode(self, n):
        p = self.T.get(n[0],Node(-1,[-1,-1])).parent
        self.T[n[0]] = Node(p,n[1:])
        for c in n[1:]:
            if c > -1:  
                cc = self.T.get(c,Node(-1,[-1,-1])).children
                self.T[c] = Node(n[0],cc)
  
    def getParent(self, i): return self.T[i].parent
  
    def getChildren(self, i): return self.T[i].children
  
    def getRoot(self, i=0):
        p = self.T[i].parent
        if p == -1: return i 
        return self.getRoot(p)
  
    def getDepth(self, i):
        if self.T[i].parent == -1: return 0
        return self.getDepth(self.T[i].parent) + 1
  
    def getHeight(self, i):
        c0 = self.T[i].children[0]
        c1 = self.T[i].children[1]
        if c0 + c1 == -2: return 0
        return max( ( 0 if c0 == -1 else self.getHeight(c0) ), \
                    ( 0 if c1 == -1 else self.getHeight(c1) ) )\
               + 1
  
    def getDegree(self, i):
        return int(self.T[i].children[0] != -1) + \
               int(self.T[i].children[1] != -1)
  
    def getNodeType(self, i):
        if self.T[i].parent == -1        : return 'root'
        if sum(self.T[i].children) == -2 : return 'leaf'
        return 'internal node'
  
    def getSibling(self, i):
        p = self.T[i].parent
        if p == -1: return -1
        return sum(self.T[p].children) - i
  
    def getIdList(self): return sorted(self.T.keys())
  
    def getPreorderList(self, i, L=[]):
        c0 = self.T[i].children[0]
        c1 = self.T[i].children[1]
        L.append(i)
        if c0 != -1: self.getPreorderList(c0, L)
        if c1 != -1: self.getPreorderList(c1, L)
        return L
  
    def getInorderList(self, i, L=[]):
        c0 = self.T[i].children[0]
        c1 = self.T[i].children[1]
        if c0 != -1: self.getInorderList(c0, L)
        L.append(i)
        if c1 != -1: self.getInorderList(c1, L)
        return L
  
    def getPostorderList(self, i, L=[]):
        c0 = self.T[i].children[0]
        c1 = self.T[i].children[1]
        if c0 != -1: self.getPostorderList(c0, L)
        if c1 != -1: self.getPostorderList(c1, L)
        L.append(i)
        return L
  
   
if __name__=='__main__':
    n = int(input())
    N = [None]*n
    for i in range(n): N[i] = list(map(int,input().split()))
    tree = my_binary_tree(N)
       
    r = tree.getRoot()
    print("Preorder")
    print("",*tree.getPreorderList(r))
    print("Inorder")
    print("",*tree.getInorderList(r))
    print("Postorder")
    print("",*tree.getPostorderList(r))

Submission status: Accepted

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

def inorder(n):
    if n != None:
        inorder(n.left)
        print n.v,
        inorder(n.right)

def preorder(n):
    if n != None:
        print n.v,
        preorder(n.left)
        preorder(n.right)

def postorder(n):
    if n != None:
        postorder(n.left)
        postorder(n.right)
        print n.v,

n = int(raw_input())
nodes = {}
root = -1
p = {}
for _ in range(n):
    nid,left,right = map(int,raw_input().split(' '))
    p[left] = nid
    p[right] = nid
    if not nid in nodes:
        nodes[nid] = Node(nid)
    if left != -1:
        if not left in nodes:
            nodes[left] = Node(left)
        nodes[nid].left = nodes[left]
    if right != -1:
        if not right in nodes:
            nodes[right] = Node(right)
        nodes[nid].right = nodes[right]

root = 0
while root in p:
    root = p[root]

tree = nodes[root]

print 'Preorder'
print '',
preorder(tree)
print
print 'Inorder'
print '',
inorder(tree)
print
print 'Postorder'
print '',
postorder(tree)
print

Submission status: Accepted

Solution code:
def preorder(i, A):
    if i == -1:
        return ""
    n = A[i]
    l = n[1]
    ls = preorder(l, A)
    r = n[2]
    rs = preorder(r, A)
    ans = " {}".format(i)
    if ls != "":
        ans += ls
    if rs != "":
        ans += rs

    return ans

def inorder(i, A):
    if i == -1:
        return ""
    n = A[i]
    l = n[1]
    ls = inorder(l, A)
    r = n[2]
    rs = inorder(r, A)
    ans = " {}".format(i)
    if ls != "":
        ans = ls + ans
    if rs != "":
        ans += rs

    return ans

def postorder(i, A):
    if i == -1:
        return ""
    n = A[i]
    l = n[1]
    ls = postorder(l, A)
    r = n[2]
    rs = postorder(r, A)
    ans = ""
    if ls != "":
        ans = ls
    if rs != "":
        ans += rs
    ans += " {}".format(i)

    return ans

n = int(input())
root = set([x for x in range(n)])

T = [None] * n
for x in range(n):
    N = list(map(int, input().split()))
    T[N[0]] = N
    root -= set(N[1:])

r = root.pop()
print("Preorder")
print(preorder(r, T[:]))

print("Inorder")
print(inorder(r, T[:]))

print("Postorder")
print(postorder(r, T[:]))

Submission status: Accepted

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: Accepted

Solution code:
#http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_7_C&lang=jp
import time
def preorder(binary_tree, target_index, result):

    result.append(target_index)
    
    left = binary_tree[target_index]["left"]
    right = binary_tree[target_index]["right"]
    if not left == -1:
        preorder(binary_tree, left, result)
    if not right == -1:
        preorder(binary_tree, right, result)

def inorder(binary_tree, target_index, result):
    
    left = binary_tree[target_index]["left"]
    right = binary_tree[target_index]["right"]
    
    if not left == -1:
        inorder(binary_tree, left, result)
    
    result.append(target_index)
    
    if not right == -1:
        inorder(binary_tree, right, result)

def postorder(binary_tree, target_index, result):
    
    left = binary_tree[target_index]["left"]
    right = binary_tree[target_index]["right"]
    
    if not left == -1:
        postorder(binary_tree, left, result)
    if not right == -1:
        postorder(binary_tree, right, result)

    result.append(target_index)
    
def make_binary_tree(node_data, node_num):
    binary_tree = [{"left":-1, "right":-1} for a in range(node_num)]
    root_index = sum([i for i in range(node_num)])

    for node in node_data:
        binary_tree[node[0]]["left"] =  node[1]
        binary_tree[node[0]]["right"] =  node[2]

        if not node[1] == -1:
            root_index -= node[1]
        if not node[2] == -1:
            root_index -= node[2]

    return root_index, binary_tree

def main():
    node_num = int(input())
    node_data = [[int(a) for a in input().split()] for i in range(node_num)]
    root_index, binary_tree = make_binary_tree(node_data, node_num)
    
    preorder_list = []
    preorder(binary_tree, root_index, preorder_list)
    print("Preorder\n", *preorder_list)
    inorder_list = []
    inorder(binary_tree, root_index, inorder_list)
    print("Inorder\n", *inorder_list)
    postorder_list = []
    postorder(binary_tree, root_index, postorder_list)
    print("Postorder\n", *postorder_list)
if __name__ == "__main__":
    main()

Submission status: Accepted

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

"""
input:
9
0 1 4
1 2 3
2 -1 -1
3 -1 -1
4 5 8
5 6 7
6 -1 -1
7 -1 -1
8 -1 -1

output:
Preorder
 0 1 2 3 4 5 6 7 8
Inorder
 2 1 3 0 6 5 7 4 8
Postorder
 2 3 1 6 7 5 8 4 0
"""

import sys


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


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

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

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

    return None


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

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

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

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

    return None


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

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

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

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

    return None


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

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

    # find root node
    root_idx = [i for i, x in enumerate(node_list) if x.parent == -1][0]

    # tree walk in 3 ways
    print('Preorder')
    pre_parse(node_list[root_idx])
    print('\n' + 'Inorder')
    in_parse(node_list[root_idx])
    print('\n' + 'Postorder')
    post_parse(node_list[root_idx])
    print('')

    return node_list


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

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

Submission status: Accepted

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

"""
input:
9
0 1 4
1 2 3
2 -1 -1
3 -1 -1
4 5 8
5 6 7
6 -1 -1
7 -1 -1
8 -1 -1

output:
Preorder
 0 1 2 3 4 5 6 7 8
Inorder
 2 1 3 0 6 5 7 4 8
Postorder
 2 3 1 6 7 5 8 4 0
"""

import sys


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


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

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

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

    return None


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

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

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

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

    return None


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

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

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

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

    return None


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

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

    # find root node
    root_idx = [i for i, x in enumerate(node_list) if x.parent == -1][0]

    # tree walk in 3 ways
    print('Preorder')
    pre_parse(node_list[root_idx])
    print('\n' + 'Inorder')
    in_parse(node_list[root_idx])
    print('\n' + 'Postorder')
    post_parse(node_list[root_idx])
    print('')

    return node_list


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

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

Submission status: Accepted

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

"""
input:
9
0 1 4
1 2 3
2 -1 -1
3 -1 -1
4 5 8
5 6 7
6 -1 -1
7 -1 -1
8 -1 -1

output:
Preorder
 0 1 2 3 4 5 6 7 8
Inorder
 2 1 3 0 6 5 7 4 8
Postorder
 2 3 1 6 7 5 8 4 0
"""

import sys


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


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

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

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

    return None


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

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

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

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

    return None


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

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

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

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

    return None


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

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

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

    # tree walk in 3 ways
    print('Preorder')
    pre_parse(node_list[root_idx])
    print('\n' + 'Inorder')
    in_parse(node_list[root_idx])
    print('\n' + 'Postorder')
    post_parse(node_list[root_idx])
    print('')

    return node_list


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

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