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:
class Node:

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

    def add_left(self, node):
        node.parent = self
        self.left = node

    def add_right(self, node):
        node.parent = self
        self.right = node

    @property
    def parent_id(self):
        if self.parent is None:
            return -1
        else:
            return self.parent.id

    @property
    def deg(self):
        count = 0
        if self.right is not None:
            count += 1
        if self.left is not None:
            count += 1
        return count

    @property
    def sibling_id(self):
        if self.parent is None or self.parent.deg == 1:
            return -1
        else:
            if self.parent.left == self:
                return self.parent.right.id if self.parent.right is not None else -1
            else:
                return self.parent.left.id if self.parent.left is not None else -1

    @property
    def node_type(self):
        if self.parent is None:
            return 'root'
        if self.left is None and self.right is None:
            return 'leaf'
        return 'internal node'

    @property
    def height(self):
        if self.left is None:
            left = -1
        else:
            left = self.left.height
        if self.right is None:
            right = -1
        else:
            right = self.right.height
        return max(left, right) + 1

    @property
    def depth(self):
        if self.parent is None:
            return 0
        else:
            return self.parent.depth + 1

    def __eq__(self, other):
        return self.id == other.id

    def __repr__(self):
        return 'node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'.format(
            self.id, self.parent_id, self.sibling_id, self.deg, self.depth, self.height, self.node_type)


def pre_parse(node, lst):
    if node is None:
        return
    lst.append(str(node.id))
    pre_parse(node.left, lst)
    pre_parse(node.right, lst)


def in_parse(node, lst):
    if node is None:
        return
    in_parse(node.left, lst)
    lst.append(str(node.id))
    in_parse(node.right, lst)


def post_parse(node, lst):
    if node is None:
        return
    post_parse(node.left, lst)
    post_parse(node.right, lst)
    lst.append(str(node.id))


def main():
    n = int(input())
    nodes = [Node(i) for i in range(n)]
    for _ in range(n):
        ID, left, right = map(int, input().split(' '))
        if left != -1:
            nodes[ID].add_left(nodes[left])
        if right != -1:
            nodes[ID].add_right(nodes[right])
    root = None
    for node in nodes:
        if node.depth == 0:
            root = node
    lst = []
    pre_parse(root, lst)
    print('Preorder')
    print(' ' + ' '.join(lst))
    lst = []
    in_parse(root, lst)
    print('Inorder')
    print(' ' + ' '.join(lst))
    lst = []
    post_parse(root, lst)
    print('Postorder')
    print(' ' + ' '.join(lst))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

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

def preParse(T, u):
    if u == -1:
        return
    print(' {}'.format(u), end='')
    preParse(T, T[u].left)
    preParse(T, T[u].right)

def inParse(T, u):
    if u == -1:
        return
    inParse(T, T[u].left)
    print(' {}'.format(u), end='')
    inParse(T, T[u].right)

def postParse(T, u):
    if u == -1:
        return
    postParse(T, T[u].left)
    postParse(T, T[u].right)
    print(' {}'.format(u), end='')

def main():
    N = int(input())
    T = [Node() for _ in range(N)]
    for _ in range(N):
        idx, l, r = map(int, input().split())
        T[idx].left = l
        T[idx].right = r
        if l != -1:
            T[l].parent = idx
        if r != -1:
            T[r].parent = idx
    root = [i for i, x in enumerate(T) if x.parent == -1][0]
    print('Preorder')
    preParse(T, root)
    print()
    print('Inorder')
    inParse(T, root)
    print()
    print('Postorder')
    postParse(T, root)
    print()

if __name__ == '__main__': main()

Submission status: Accepted

Solution code:
import sys


class Node():

	def __init__(self,id,left,right):
		
		self.id = id
		self.left = left
		self.right = right
		self.parent = -1
		self.sibling = -1
		self.degree = 0
		self.depth = 0
		self.height = 0

def define_depth(Nodes,node):

	if node.left == -1 and node.right == -1: #leaf
		return

	if node.left != -1:
		Nodes[node.left].depth = node.depth + 1
		define_depth(Nodes,Nodes[node.left])
	if node.right != -1:
		Nodes[node.right].depth = node.depth + 1
		define_depth(Nodes,Nodes[node.right])

def define_height(Nodes,node):

	h1 = 0
	h2 = 0

	if node.left != -1:
		h1 += define_height(Nodes,Nodes[node.left]) + 1
	if node.right != -1:
		h2 += define_height(Nodes,Nodes[node.right]) + 1

	return max(h1,h2)

def find_root(Nodes,node):

	if node.parent == -1:
		return node.id

	return find_root(Nodes,Nodes[node.parent])

def print_nodes(Nodes,node_id,type,output):

	#TYPE
	#0 : Preorder
	#1 : Inorder
	#2 : Postorder

	if node_id == -1:
		return

	if type == 0:
		output.append(node_id)

	print_nodes(Nodes,Nodes[node_id].left,type,output)
	if type == 1:
		output.append(node_id)
	print_nodes(Nodes,Nodes[node_id].right,type,output)
	if type == 2:
		output.append(node_id)

def test():

	n = int(sys.stdin.readline())
	Nodes = [Node(0,0,0)] * n
	root = 0

	# Reading inputs
	for i in range(n):

		inputs = list(map(int,sys.stdin.readline().split()))
		id = inputs[0]
		left = inputs[1]
		right = inputs[2]

		tmp_node = Node(id,left,right)
		Nodes[id] = tmp_node

	# Defining parent and sibling and root
	for node in Nodes:

		child_count = 0

		# Parent
		if node.right != -1:
			Nodes[node.right].parent = node.id
			child_count += 1
		if node.left != -1:
			Nodes[node.left].parent = node.id
			child_count += 1

		# Degree
		node.degree = child_count

		#Sibling
		if node.right != -1 and node.left != -1:
			Nodes[node.right].sibling = node.left
			Nodes[node.left].sibling = node.right

	# Finding root
	root = find_root(Nodes,Nodes[0])

	# Defining depth
	define_depth(Nodes,Nodes[root])

	# Defining height
	for node in Nodes:
		node.height = define_height(Nodes,node)

	output = []

	# Printing Nodes
	print_nodes(Nodes,Nodes[root].id,0,output)
	print("Preorder")
	for i in range(n):
		print(f" {output[i]}",end='')
	print()
	
	output.clear()
	print_nodes(Nodes,Nodes[root].id,1,output)
	print("Inorder")
	for i in range(n):
		print(f" {output[i]}",end='')
	print()

	output.clear()
	print_nodes(Nodes,Nodes[root].id,2,output)
	print("Postorder")
	for i in range(n):
		print(f" {output[i]}",end='')
	print()

if __name__ == "__main__":
	test()

Submission status: Accepted

Solution code:
n = int(input())

"""親情報を入れる'p'、左の子を入れる'l'、右の子を入れる'r'の辞書を作成"""
p, l, r = {}, {}, {}

for i in range(n):
    num, left, right = input().split()
    l[num] = left
    r[num] = right
    if left != '-1':
        p[left] = num
    if right != '-1':
        p[right] = num

root = (set(l) - set(p)).pop()

def preorder(num):
    if num == '-1':
        return
    print(' ' + num, end='')
    preorder(l[num])
    preorder(r[num])

def inorder(num):
    if num == '-1':
        return
    inorder(l[num])
    print(' ' + num, end='')
    inorder(r[num])

def postorder(num):
    if num == '-1':
        return
    postorder(l[num])
    postorder(r[num])
    print(' ' + num, end='')

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

Submission status: Accepted

Solution code:
class binaryTreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

n = int(input())
hashMap = {}
rootL = list(range(n))
for index in range(n):
    inputL = list(map(int, input().split()))
    if not inputL[0] in hashMap:
        hashMap[inputL[0]] = binaryTreeNode(inputL[0])
    parent = hashMap[inputL[0]]
    if inputL[1] != -1:
        rootL.remove(inputL[1])
        if not inputL[1] in hashMap:
            hashMap[inputL[1]] = binaryTreeNode(inputL[1])
        parent.left = hashMap[inputL[1]]
    if inputL[2] != -1:
        rootL.remove(inputL[2])
        if not inputL[2] in hashMap:
            hashMap[inputL[2]] = binaryTreeNode(inputL[2])
        parent.right = hashMap[inputL[2]]

root = hashMap[rootL[0]]
print('Preorder')
preL = []
def lookNodePre(node):
    if node != None:
        preL.append(node.val)
        lookNodePre(node.left)
        lookNodePre(node.right)
lookNodePre(root)
print(' '+' '.join(list(map(str, preL))))

print('Inorder')
InL = []
def lookNodeIn(node):
    if node != None:
        lookNodeIn(node.left)
        InL.append(node.val)
        lookNodeIn(node.right)
lookNodeIn(root)
print(' '+' '.join(list(map(str, InL))))

print('Postorder')
postL = []
def lookNodePost(node):
    if node != None:
        lookNodePost(node.left)
        lookNodePost(node.right)
        postL.append(node.val)
lookNodePost(root)
print(' '+' '.join(map(str, postL)))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from collections import deque

n = int(input())
P = [-1]*n
C = [[] for i in range(n)]
Pre, In, Post = [], [], []

for i in range(n):
  s = [int(i) for i in input().split()]
  id = s[0]
  l = s[1]
  r = s[2]
  C[id] = (l,r)
  if l != -1:
    P[l] = id
  if r != -1:
    P[r] = id

for i in range(n):
  if P[i] == -1:
    root = i

def Prewalk(x):
  Pre.append(x)
  l,r = C[x]
  if l == -1 and r == -1:
    return
  if l != -1:
    Prewalk(l)
  if r != -1:
    Prewalk(r)
  
def Inwalk(x):
  l,r = C[x]
  if l == -1 and r == -1:
    In.append(x)
    return
  if l != -1:
    Inwalk(l)
  In.append(x)
  if r != -1:
    Inwalk(r)
  
def Postwalk(x):
  l,r = C[x]
  if l == -1 and r == -1:
    Post.append(x)
    return
  if l != -1:
    Postwalk(l)
  if r != -1:
    Postwalk(r)
  Post.append(x)
  
Prewalk(root)
Inwalk(root)
Postwalk(root)

print("Preorder")
print(" "+" ".join(map(str, Pre)))
print("Inorder")
print(" "+" ".join(map(str, In)))
print("Postorder")
print(" "+" ".join(map(str, Post)))

Submission status: Accepted

Solution code:
n=int(input())
data=[list(map(int,input().split())) for i in range(n)]
data.sort(key=lambda tup:tup[0])
parent=[-1]*n

for i in range(n):
    if data[i][1]!=-1:
        parent[data[i][1]]=i
    if data[i][2]!=-1:
        parent[data[i][2]]=i

for i in range(n):
    if parent[i]==-1:
        root=i

def preorder(node):
    if node==-1:return
    print(' '+str(node),end='')
    preorder(data[node][1])
    preorder(data[node][2])

def inorder(node):
    if node==-1:return
    inorder(data[node][1])
    print(' '+str(node),end='')
    inorder(data[node][2])

def postorder(node):
    if node==-1:return
    postorder(data[node][1])
    postorder(data[node][2])    
    print(' '+str(node),end='')

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

Submission status: Accepted

Solution code:
class node:
    def __init__(self, parent, left, right):
        self.parent=parent
        self.left=left
        self.right=right

class tree:

    def __init__(self, datas):
        #format of datas
        #id, left, right
        self.T=[]
        self.rootID=None
        for d in datas:
            self.T.append(node(None,None, None))

        for d in datas:
            if(d[1]!=-1):
                self.T[d[0]].left=d[1]
            if(d[2]!=-1):
                self.T[d[0]].right=d[2]

        for d in datas:

            id=d[0]
            if(self.T[id].left is not None):
                self.T[self.T[id].left].parent = id
            if (self.T[id].right is not None):
                self.T[self.T[id].right].parent = id


        for d in datas:
            if(self.T[d[0]].parent is None):
                self.rootID = d[0]
                #print(rootid)

        self.Preorder = [None for _ in datas]
        self.Inorder =[None for _ in datas]
        self.Postorder=[None for _ in datas]

        self.setPreorder(self.rootID)
        self.setInorder(self.rootID)
        self.setPostorder(self.rootID)

        #print(self.Preorder)
        #print(self.Inorder)
        #print(self.Postorder)


    def setPreorder(self, id):
        if id is None:
            return
        else:
            self.Preorder.append(id)
            self.setPreorder(self.T[id].left)
            self.setPreorder(self.T[id].right)

    def setInorder(self,id):
        if id is None:
            return
        else:
            self.setInorder(self.T[id].left)
            self.Inorder.append(id)
            self.setInorder(self.T[id].right)

    def setPostorder(self,id):
        if id is None:
            return
        else:
            self.setPostorder(self.T[id].left)
            self.setPostorder(self.T[id].right)
            self.Postorder.append(id)

n=int(input())
dlist=[]
for i in range(n):
    dlist.append(list(map(int,(input().split()))))
t=tree(dlist)
print("Preorder")
print(" "+" ".join([str(_) for _ in t.Preorder if _ is not None]))
print("Inorder")
print(" "+" ".join([str(_) for _ in t.Inorder if _ is not None]))
print("Postorder")
print(" "+" ".join([str(_) for _ in t.Postorder if _ is not None]))

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10**6)


class Node:
    def __init__(self, p, l, r):
        self.p = p
        self.l = l
        self.r = r


N = int(input())
T = [Node(-1, -1, -1) for _ in range(N)]


def preorder_parse(u):
    if u == -1:
        return
    print(' ' + str(u), end='')
    preorder_parse(T[u].l)
    preorder_parse(T[u].r)


def inorder_parse(u):
    if u == -1:
        return
    inorder_parse(T[u].l)
    print(' ' + str(u), end='')
    inorder_parse(T[u].r)


def postorder_parse(u):
    if u == -1:
        return
    postorder_parse(T[u].l)
    postorder_parse(T[u].r)
    print(' ' + str(u), end='')


def main():
    for _ in range(N):
        v, l, r = map(int, input().split())
        T[v].l = l
        T[v].r = r
        if l != -1:
            T[l].p = v
        if r != -1:
            T[r].p = v

    root = 0
    for i, t in enumerate(T):
        if t.p == -1:
            root = i

    print('Preorder')
    preorder_parse(root)
    print('')
    print('Inorder')
    inorder_parse(root)
    print('')
    print('Postorder')
    postorder_parse(root)
    print('')


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

n=int(input())
T=[[]]*n
P=[-1]*(n+1)#n=1の対策、場当たり的だが
for i in range(n):
    id, left, right = map(int,input().split( ))
    T[id] =[left,right]
    P[right] = id
    P[left] = id

root=0

while P[root] !=-1:
    root = P[root]

#再帰的に行う

def preorder(u):
    global T
    L = []
#    if u != -1:
#        L.append(u)
#        L += (preorder(T[u][0]))
#        L += (preorder(T[u][1]))
#他も同様の変更
    L.append(u)
    if T[u][0] != -1:
        L += (preorder(T[u][0]))
    if T[u][1] != -1:
        L += (preorder(T[u][1]))
    return L

def inorder(u):
    global T
    L = []
    if T[u][0] != -1:
        L += (inorder(T[u][0]))
    L.append(u)
    if T[u][1] != -1:
        L += (inorder(T[u][1]))
    return L


def postorder(u):
    global T
    L = []
    if T[u][0] != -1:
        L += (postorder(T[u][0]))
    if T[u][1] != -1:
        L += (postorder(T[u][1]))
    L.append(u)
    return L
Pre= preorder(root)
In = inorder(root)
Post=postorder(root)
print("Preorder",end="\n ")
print(*Pre)
print("Inorder",end="\n ")
print(*In)
print("Postorder",end="\n ")
print(*Post)

Submission status: Accepted

Solution code:

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


def preorder(id):
    print(" {}".format(id), end="")

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


def inorder(id):
    if Nodes[id].left != -1:
        inorder(Nodes[id].left)

    print(" {}".format(id), end="")

    if Nodes[id].right != -1:
        inorder(Nodes[id].right)


def postorder(id):
    if Nodes[id].left != -1:
        postorder(Nodes[id].left)

    if Nodes[id].right != -1:
        postorder(Nodes[id].right)

    print(" {}".format(id), end="")


def main():
    n = int(input())
    global Nodes
    Nodes = [Node() for i in range(n)]

    for i in range(n):
        id, *children = map(int, input().split())
        left = children[0]
        right = children[1]
        Nodes[id].left = left
        Nodes[id].right = right
        for child in children:
            if child != -1:
                Nodes[child].parent = id

    rootid = ""
    for i, node in enumerate(Nodes):
        if node.parent == -1:
            rootid = i

    print("Preorder")
    preorder(rootid)
    print()

    print("Inorder")
    inorder(rootid)
    print()

    print("Postorder")
    postorder(rootid)
    print()


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
class Node:
    def __init__(self, p=-1, l=-1, r=-1):
        self._p = p
        self._l = l
        self._r = r

T = []

def pre_parse(index):
    if index == -1:
        return
    print(' %d'%index, end='')
    pre_parse(T[index]._l)
    pre_parse(T[index]._r)

def in_parse(index):
    if index == -1:
        return
    in_parse(T[index]._l)
    print(' %d'%index, end='')
    in_parse(T[index]._r)

def post_parse(index):
    if index == -1:
        return
    post_parse(T[index]._l)
    post_parse(T[index]._r)
    print(' %d'%index, end='')

if __name__ == '__main__':
    n = int(input())

    for i in range(n):
        T.append(Node(-1, -1, -1))

    for i in range(n):
        index, l_child, r_child = map(int, input().split())
        T[index]._l = l_child
        T[index]._r = r_child
        if l_child != -1:
            T[l_child]._p = index
        if r_child != -1:
            T[r_child]._p = index

    root = -1
    for i in range(n):
        if T[i]._p == -1:
            root = i
            break

    print('Preorder')
    pre_parse(root)
    print('\nInorder')
    in_parse(root)
    print('\nPostorder')
    post_parse(root)
    print()

Submission status: Accepted

Solution code:
def print_preorder(node: int) -> None:
    global trees
    print(f" {node}", end="")
    left_child = trees[node]['left-child']
    right_child = trees[node]['right-child']
    if -1 != left_child:
        print_preorder(left_child)
    if -1 != right_child:
        print_preorder(right_child)


def print_inorder(node: int) -> None:
    global trees
    left_child = trees[node]['left-child']
    right_child = trees[node]['right-child']
    if -1 != left_child:
        print_inorder(left_child)
    print(f" {node}", end="")
    if -1 != right_child:
        print_inorder(right_child)


def print_postorder(node: int) -> None:
    global trees
    left_child = trees[node]['left-child']
    right_child = trees[node]['right-child']
    if -1 != left_child:
        print_postorder(left_child)
    if -1 != right_child:
        print_postorder(right_child)
    print(f" {node}", end="")


if __name__ == "__main__":
    node_num = int(input())
    trees = {idx:
             {"parent": -1, "left-child": -1, "right-child": -1}
             for idx in range(node_num)}

    for _ in range(0, node_num):
        node, left_child, right_child = map(lambda x: int(x), input().split())
        if -1 != left_child:
            trees[node]["left-child"] = left_child
            trees[left_child]["parent"] = node
        if -1 != right_child:
            trees[node]["right-child"] = right_child
            trees[right_child]["parent"] = node

    root_node = [k for k, v in trees.items() if v["parent"] == -1][0]

    print("Preorder")
    print_preorder(root_node)
    print("")
    print("Inorder")
    print_inorder(root_node)
    print("")
    print("Postorder")
    print_postorder(root_node)
    print("")

Submission status: Accepted

Solution code:
class Node2:
    def __init__(self):
        self.parent = -1
        self.left = -1
        self.right = -1
    
def getSibling(u):
    if Nodes[u].parent == -1:
        return -1
    p = Nodes[u].parent
    if Nodes[p].left == u:
        return Nodes[p].right
    else:
        return Nodes[p].left

def getDepth(u):
    depth = 0
    while Nodes[u].parent != -1:
        depth += 1
        u = Nodes[u].parent
        
    return depth

def getDegree(u):
    if Nodes[i].left != -1 and Nodes[i].right != -1:
        return 2
    elif Nodes[i].left == -1 and Nodes[i].right == -1:
        return 0
    else:
        return 1

def getHeight(u):
    a = 0
    b = 0
    if Nodes[u].left != -1:
        a = getHeight(Nodes[u].left) + 1
    if Nodes[u].right != -1:
        b = getHeight(Nodes[u].right) + 1
    return max(a, b)

def getType(u):
    if Nodes[u].parent == -1:
        return "root"
    elif Nodes[u].right != -1 or Nodes[u].left != -1:
        return "internal node"
    else:
        return "leaf"
    
def printNode(u):
    print_str = "node " + str(u) + ": parent = " + str(Nodes[u].parent) + ", "
    print_str = print_str + "sibling = " + str(getSibling(u)) + ", "
    print_str = print_str + "degree = " + str(getDegree(u)) + ", "
    print_str = print_str + "depth = " + str(getDepth(u)) + ", "
    print_str = print_str + "height = " + str(getHeight(u)) + ", " + getType(u)
    print(print_str)

def getRoot(u):
    if Nodes[u].parent == -1:
        return u
    return getRoot(Nodes[u].parent)

    
def printPreorder(u):
    if u == -1:
        return
    print(" ", u, sep="", end="")
    printPreorder(Nodes[u].left)
    printPreorder(Nodes[u].right)
    
def printInorder(u):
    if u == -1:
        return
    printInorder(Nodes[u].left)
    print(" ", u, sep="", end="")
    printInorder(Nodes[u].right)
    
def printPostorder(u):
    if u == -1:
        return
    printPostorder(Nodes[u].left)
    printPostorder(Nodes[u].right)
    print(" ", u, sep="", end="")
    
# 入力
n = int(input())

Nodes = []
for i in range(n):
    tmp_obj = Node2()
    Nodes.append(tmp_obj)

# 登録作業
for i in range(n):
    num, left, right = map(int, input().split())
    Nodes[num].left = left
    Nodes[num].right = right
    if left != -1:
        Nodes[left].parent = num
    if right != -1:
        Nodes[right].parent = num

root = getRoot(0)
        
print("Preorder")
printPreorder(root)
print("\nInorder")
printInorder(root)
print("\nPostorder")
printPostorder(root)
print("")

Submission status: Accepted

Solution code:
INDEX_LEFT = 0
INDEX_RIGHT = 1


# INPUT
n = int(input())

list_child = [[] for _ in range(n)]
list_parent = [-1 for _ in range(n)]

for _ in range(n):

    id, *C = map(int, input().split())

    list_child[int(id)].extend(C)

    for c in C:
        if c == -1:
            continue

        list_parent[int(c)] = int(id)


# PROCESS
def treewalk_preorder(u):
    if u == -1:
        return

    print(f" {u}", end="")
    treewalk_preorder(list_child[u][INDEX_LEFT])
    treewalk_preorder(list_child[u][INDEX_RIGHT])


def treewalk_inorder(u):
    if u == -1:
        return

    treewalk_inorder(list_child[u][INDEX_LEFT])
    print(f" {u}", end="")
    treewalk_inorder(list_child[u][INDEX_RIGHT])


def postorder_treewalk(u):
    if u == -1:
        return

    postorder_treewalk(list_child[u][INDEX_LEFT])
    postorder_treewalk(list_child[u][INDEX_RIGHT])
    print(f" {u}", end="")


root = list_parent.index(-1)

# OUTPUT
print("Preorder")
treewalk_preorder(root)
print()

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

print("Postorder")
postorder_treewalk(root)
print()

Submission status: Accepted

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

    def getId(self):
        return self.id

    def setRight(self, right):
        self.right = right

    def setLeft(self, left):
        self.left = left

    def getLeft(self):
        return self.left

    def setParent(self, parent):
        self.parent = parent

    def isRoot(self):
        return self.parent is None

    def preorder(self):
        print('', self.id, end='')
        if self.left is not None:
            self.left.preorder()
        if self.right is not None:
            self.right.preorder()

    def inorder(self):
        if self.left is not None:
            self.left.inorder()
        print('', self.id, end='')
        if self.right is not None:
            self.right.inorder()

    def postorder(self):
        if self.left is not None:
            self.left.postorder()
        if self.right is not None:
            self.right.postorder()
        print('', self.id, end='')

    def printInfo(self):
        if self.left is None:
            left = -1
        else:
            left = self.left.getId()
        if self.right is None:
            right = -1
        else:
            right = self.right.getId()
        print("{} {} {}".format(self.id, left, right))

n = int(input())

nodes = []

for i in range(n):
    nodes.append(Node(i))

for i in range(n):
    id, left, right = map(int, input().split())
    if left != -1:
        nodes[id].setLeft(nodes[left])
        nodes[left].setParent(nodes[id])
    if right != -1:
        nodes[id].setRight(nodes[right])
        nodes[right].setParent(nodes[id])

def getRootNode(nodes):
    for e in nodes:
        if e.isRoot():
            return e
    return None

def getLeftNode(nodes):
    node = getRootNode(nodes)
    while True:
        left = node.getLeft()
        if left is not None:
            node = left
        else:
            return node
    return None

def preorder(nodes):
    print('Preorder')
    root = getRootNode(nodes)
    root.preorder()
    print('')

def inorder(nodes):
    print('Inorder')
    root = getRootNode(nodes)
    root.inorder()
    print('')

def postorder(nodes):
    print('Postorder')
    root = getRootNode(nodes)
    root.postorder()
    print('')

preorder(nodes)
inorder(nodes)
postorder(nodes)