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.

Solution (Python):
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()

Solution (Python):
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: 
		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):

	
	
	
	

	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

	
	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

	
	for node in Nodes:

		child_count = 0

		
		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

		
		node.degree = child_count

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

	
	root = find_root(Nodes,Nodes[0])

	
	define_depth(Nodes,Nodes[root])

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

	output = []

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

Solution (Python):
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()

Solution (Python):
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)))

Solution (Python):
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)))

Solution (Python):
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()

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

class tree:

    def __init__(self, datas):
        
        
        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]
                

        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)

        
        
        


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

Solution (Python):
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()

Solution (Python):

n=int(input())
T=[[]]*n
P=[-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 = []





    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)

Solution (Python):

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

Solution (Python):
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()

Solution (Python):
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("")

Solution (Python):
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("")

Solution (Python):
INDEX_LEFT = 0
INDEX_RIGHT = 1



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)



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)


print("Preorder")
treewalk_preorder(root)
print()

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

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

Solution (Python):
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)

Solution (Python):
import sys
sys.setrecursionlimit(10**7)

nodedict = {}

preorder_list = []
inorder_list = []
postorder_list = []

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

        self.walked = False

    def __repr__(self):
        return str(self.__dict__)

    def get_height(self):
        if self.height != -1:
            pass
        else:
            if self.degree == 0:
                self.height = 0
            else:
                lh, rh = 0, 0
                if self.left != -1:
                    lh = nodedict[self.left].get_height()
                if self.right != -1:
                    rh = nodedict[self.right].get_height()
                self.height = max(lh, rh) + 1

        return self.height

    def preorder(self):
        if self.walked:
            return 0

        self.walked = True
        preorder_list.append(self.id)

        if self.left != -1:
            nodedict[self.left].preorder()
        if self.right != -1:
            nodedict[self.right].preorder()
        return 0


    def inorder(self):
        if self.walked:
            return 0

        if self.left != -1:
            nodedict[self.left].inorder()

        self.walked = True
        inorder_list.append(self.id)

        if self.right != -1:
            nodedict[self.right].inorder()
        return 0

    def postorder(self):
        if self.walked:
            return 0

        if self.left != -1:
            nodedict[self.left].postorder()


        if self.right != -1:
            nodedict[self.right].postorder()
        self.walked = True
        postorder_list.append(self.id)
        return 0


def assign_info(node, current_depth):
    node.depth = current_depth
    if node.left != -1:
        left = nodedict[node.left]
        left.parent = node.id
        left.sibling = node.right
        assign_info(left, current_depth + 1)

    if node.right != -1:
        right = nodedict[node.right]
        right.parent = node.id
        right.sibling = node.left
        assign_info(right, current_depth + 1)

def clear_flag():
    for k in nodedict.keys():
        node = nodedict[k]
        node.walked = False

def solve():
    n = int(input())

    
    childlist = []
    for i in range(n):
        id, left, right = map(int, input().split())
        nodedict[id] = Node(id, left, right)
        childlist.append(left)
        childlist.append(right)

    
    rootid = -1
    for i in range(n):
        if i not in childlist:
            rootid = i

    
    assign_info(nodedict[rootid], 0)

    
    
    

    
    nodedict[rootid].preorder()
    print("Preorder")
    print(' ' + ' '.join([str(i) for i in preorder_list]))
    clear_flag()

    
    nodedict[rootid].inorder()
    print("Inorder")
    print(' ' + ' '.join([str(i) for i in inorder_list]))
    clear_flag()

    
    nodedict[rootid].postorder()
    print("Postorder")
    print(' ' + ' '.join([str(i) for i in postorder_list]))

    
    
    
    
    
    
    
    
    
    
    
    

solve()

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

n = int(input())
T = [Node(i) for i in range(n)]
for ni in range(n):
    idn, left, right = [int(i) for i in input().split()]
    T[idn].left = left
    T[idn].right = right
    if left != -1:
        T[left].parent = idn
    if right != -1:
        T[right].parent = idn

i = 0
while T[i].parent != -1:
    i = T[i].parent
root = i

orderList = []
def setPreorderList(p):
    orderList.append(T[p].id)
    if T[p].left != -1:
        setPreorderList(T[p].left)
    if T[p].right != -1:
        setPreorderList(T[p].right)

setPreorderList(root)
print("Preorder")
print("",*orderList)

orderList = []
def setInorderList(p):
    if T[p].left != -1:
        setInorderList(T[p].left)
    orderList.append(T[p].id)
    if T[p].right != -1:
        setInorderList(T[p].right)

setInorderList(root)
print("Inorder")
print("",*orderList)

orderList = []
def setPostorderList(p):
    if T[p].left != -1:
        setPostorderList(T[p].left)
    if T[p].right != -1:
        setPostorderList(T[p].right)
    orderList.append(T[p].id)

setPostorderList(root)
print("Postorder")
print("",*orderList)

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


n = int(input())
node  = [list(map(int, input().split())) for _ in range(n)] 
result = [Node() for _ in range(n)]
D = [0 for _ in range(n)]
H = [0 for _ in range(n)]


def initiate(li):
  for l in li:
    n = l[0]
    left = l[1]
    right = l[2]
    if left != -1:
      result[left].parent = n
      result[n].left = left
    if right != -1:
      result[right].parent = n
      result[n].right = right

post_list = []
pre_list = []
in_list = []

def preorder(li, root):
  pre_list.append(root)
  if li[root].left != -1:
    preorder(li, li[root].left)
  if li[root].right != -1:
    preorder(li, li[root].right)
  return 

def inorder(li, root):
  if li[root].left != -1:
    inorder(li, li[root].left)
  in_list.append(root)
  if li[root].right != -1:
    inorder(li, li[root].right)
  return 

def postorder(li, root):
  if li[root].left != -1:
    postorder(li, li[root].left)
  if li[root].right != -1:
    postorder(li, li[root].right)
  post_list.append(root)
  return

initiate(node)
root = 0
for i in range(n):
  if result[i].parent == -1:
    root = i 
    break


preorder(result, root)
pre_list = list(map(str, pre_list))
inorder(result, root)
in_list = list(map(str, in_list))
postorder(result, root)
post_list = list(map(str, post_list))

final = []

print("Preorder")
print("", ' '.join(pre_list))
print("Inorder")
print(""," ".join(in_list))
print("Postorder")
print(""," ".join(post_list))

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

def preorder(ns, i):
  print(" " + str(i), end = "")
  if ns[i].left != -1:
    preorder(ns, ns[i].left)
  if ns[i].right != -1:
    preorder(ns, ns[i].right)

def inorder(ns, i):
  if ns[i].left != -1:
    inorder(ns, ns[i].left)
  print(" " + str(i), end = "")
  if ns[i].right != -1:
    inorder(ns, ns[i].right)

def postorder(ns, i):
  if ns[i].left != -1:
    postorder(ns, ns[i].left)
  if ns[i].right != -1:
    postorder(ns, ns[i].right)
  print(" " + str(i), end = "")

n = int(input())
ns = [Node() for i in range(n)]
for i in range(n):
  p, l, r = map(int, input().split())
  if l != -1:
    ns[p].left = l
    ns[l].parent = p
  if r != -1:
    ns[p].right = r
    ns[r].parent = p 

for i in range(n):
  if ns[i].parent == -1:
    print("Preorder")
    preorder(ns, i)
    print()
    print("Inorder")
    inorder(ns, i)
    print()
    print("Postorder")
    postorder(ns, i)
    print()