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
readline = sys.stdin.readline
write= sys.stdout.write
N = int(readline())
L = [None]*N; R = [None]*N; P = [-1]*(N+1)
for i in range(N):
    i, l, r = map(int, readline().split())
    L[i] = l; R[i] = r
    P[l] = i; P[r] = i
s0 = []; s1 = []; s2 = []
def dfs(v):
    v0 = str(v)
    s0.append(v0)
    L[v] != -1 and dfs(L[v])
    s1.append(v0)
    R[v] != -1 and dfs(R[v])
    s2.append(v0)
dfs(P.index(-1))
write("Preorder\n %s\nInorder\n %s\nPostorder\n %s\n" % tuple(map(" ".join, [s0, s1, s2])))

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

Solution (Python):

class Node():
    "node of the tree structure"
    def __init__(self, parent = -1, left = -1, right = -1):
        self.parent = parent
        self.left = left
        self.right = right
def preParse(u):
    if u == -1:
        return
    list_preParse.append(u)
    preParse(node_list[u].left)
    preParse(node_list[u].right)

def inParse(u):
    if u == -1:
        return
    inParse(node_list[u].left)
    list_inParse.append(u)
    inParse(node_list[u].right)

def postParse(u):
    if u == -1:
        return
    postParse(node_list[u].left)
    postParse(node_list[u].right)
    list_postParse.append(u)

def returnRoot(u):
    while node_list[u].parent != -1:
        u = node_list[u].parent
    return u

list_preParse = []
list_inParse = []
list_postParse = []
n = int(input())
node_list = []
for i in range(n):
    node = Node()
    node_list.append(node)

for i in range(n):
    a,b,c = map(int, input().split())
    node_list[a].left = b
    node_list[a].right = c
    if b != -1:
        node_list[b].parent = a
    if c != -1:
        node_list[c].parent = a

print("Preorder")
preParse(returnRoot(0))
for i in range(n):
    list_preParse[i] = str(list_preParse[i])
print(" " + " ".join(list_preParse))

print("Inorder")
inParse(returnRoot(0))
for i in range(n):
    list_inParse[i] = str(list_inParse[i])
print(" " + " ".join(list_inParse))
print("Postorder")
postParse(returnRoot(0))
for i in range(n):
    list_postParse[i] = str(list_postParse[i])
print(" " + " ".join(list_postParse))

Solution (Python):
import heapq
from collections import deque
from enum import Enum
import sys
import math
from _heapq import heappush, heappop

BIG_NUM = 2000000000
HUGE_NUM = 9999999999999999
MOD = 1000000007
EPS = 0.000000001


global nodes

class Node:
    def __init__(self):
        self.left = -1
        self.right = -1
    def set(self,arg_node_left,arg_node_right):
        self.left = arg_node_left
        self.right = arg_node_right


def Preorder(node_id):
    print(" %d"%(node_id),end = "")

    if nodes[node_id].left != -1:
        Preorder(nodes[node_id].left)

    if nodes[node_id].right != -1:
        Preorder(nodes[node_id].right)


def Inorder(node_id):

    if nodes[node_id].left != -1:
        Inorder(nodes[node_id].left)

    print(" %d"%(node_id),end = "")

    if nodes[node_id].right != -1:
        Inorder(nodes[node_id].right)


def Postorder(node_id):

    if nodes[node_id].left != -1:
        Postorder(nodes[node_id].left)

    if nodes[node_id].right != -1:
        Postorder(nodes[node_id].right)

    print(" %d"%(node_id),end = "")




V = int(input())
nodes = [Node() for _ in range(V)]
in_num = [0]*V


for loop in range(V):
    node_id,left,right = map(int,input().split())
    nodes[node_id].set(left,right)
    if left != -1:
        in_num[left] += 1
    if right != -1:
        in_num[right] += 1

root = -1

for i in range(V):
    if in_num[i] == 0:
        root = i
        break

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

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

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

Solution (Python):

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

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[l].parent = p 
        ns[p].left = l
    if (r != -1):
        ns[r].parent = p
        ns[p].right = r
        
        
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 = '')  

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

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


def preorder(id):
    print(f" {id}", end="")
    if tree[id].left is not None:
        preorder(tree[id].left)
    if tree[id].right is not None:
        preorder(tree[id].right)

def inorder(id):
    if tree[id].left is not None:
        inorder(tree[id].left)
    print(f" {id}", end="")
    if tree[id].right is not None:
        inorder(tree[id].right)


def postorder(id):
    if tree[id].left is not None:
        postorder(tree[id].left)
    if tree[id].right is not None:
        postorder(tree[id].right)
    print(f" {id}", end="")
    
n = int(input())
tree = []
for _ in range(n):
    tree.append(Node())
for _ in range(n):
    id, left, right = map(int, input().split())
    if left != -1:
        tree[id].left = left
        tree[left].parent = id
    if right != -1:
        tree[id].right = right
        tree[right].parent = id
        
for id in range(n):
    if tree[id].parent is None:
        root_id = id
        break
    
print("Preorder")
preorder(root_id)
print("")
print("Inorder")
inorder(root_id)
print("")
print("Postorder")
postorder(root_id)
print("")

Solution (Python):
def pre_order(u):
    if u == -1:
        return
    print('', u, end='')
    pre_order(T[u])
    pre_order(T[u + N])

def in_order(u):
    if u == -1:
        return
    in_order(T[u])
    print('', u, end='')
    in_order(T[u + N])

def post_order(u):
    if u == -1:
        return
    post_order(T[u])
    post_order(T[u + N])
    print('', u, end='')

N = int(input())
T = [0, 0] * N
for _ in range(N):
    a, b, c = map(int, input().split())
    T[a], T[a + N] = b, c
root = (set(range(N)) - set(T)).pop()
print('Preorder')
pre_order(root)
print('\nInorder')
in_order(root)
print('\nPostorder')
post_order(root)
print()

Solution (Python):
class Node:
    def __init__(self, nid):
        self.nid = nid
        self.parent = None
        self.left = None
        self.right = None
    
    def preo(self):
        tmp = ""
        tmp += " " + str(self.nid)
        if self.left:
            tmp += self.left.preo()
        if self.right:
            tmp += self.right.preo()
        return tmp
    
    def ino(self):
        tmp = ""
        if self.left:
            tmp += self.left.ino()
        tmp += " " + str(self.nid)
        if self.right:
            tmp += self.right.ino()
        return tmp
    
    def posto(self):
        tmp = ""
        if self.left:
            tmp += self.left.posto()
        if self.right:
            tmp += self.right.posto()
        tmp += " " + str(self.nid) 
        return tmp
    
n = int(input())
T={}
for i in range(n):
    T[i] = Node(i)
for i in range(n):
    nid, left, right = [int(i) for i in input().split()]
    if left != -1:
        T[nid].left = T[left]
        T[left].parent = T[nid]
    if right != -1:
        T[nid].right = T[right]
        T[right].parent = T[nid]
root = T[0]
while(True):
    if root.parent:
        root = root.parent
    else:
        break
print("Preorder")
print(root.preo())
print("Inorder")
print(root.ino())
print("Postorder")
print(root.posto())

Solution (Python):
NIL = -1

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


def preParse(tree, u):
    if u == NIL:
        return
    print(' %d' % u, end='')
    preParse(tree, tree[u].left)
    preParse(tree, tree[u].right)


def inParse(tree, u):
    if u == NIL:
        return
    inParse(tree, tree[u].left)
    print(' %d' % u, end='') 
    inParse(tree, tree[u].right)


def postParse(tree, u):
    if u == NIL:
        return
    postParse(tree, tree[u].left)
    postParse(tree, tree[u].right)
    print(' %d' % u, end='') 


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

for i in range(n):
    value, left, right = [int(v) for v in input().split()]
    tree[value].left = left
    tree[value].right = right
    if left != NIL:
        tree[left].parent = value
    if right != NIL:
        tree[right].parent = value

root = 0
for i in range(n):
    if tree[i].parent == NIL:
        root = i
        break

print('Preorder')
preParse(tree, root)
print()
print('Inorder')
inParse(tree, root)
print()
print('Postorder')
postParse(tree, root)
print()

Solution (Python):

class Node:
    none = 0
    right = 1
    left = -1
    def is_leaf(self):
        d = 1 if self.right else 0
        d += 1 if self.left else 0
        return self.depth > 0 and d == 0
    def num_child(self):
        d = 1 if self.right else 0
        d += 1 if self.left else 0
        return d
    
    def __init__(self, id):
        self.id = id
        self.parent = None
        self.sibling = None
        
        self.right,self.left = None,None
        self.depth = 0
        self.height = 0
        self.position = Node.none
    def __str__(self):
        p = self.parent.id if self.parent else -1
        s = self.sibling.id if self.sibling else -1
        d = 1 if self.right else 0
        d += 1 if self.left else 0
        typ = 'root'
        if self.depth > 0: typ = 'internal node'
        if d == 0 and self.depth > 0: typ = 'leaf'
        h = self.height
        return 'node {0}: parent = {1}, sibling = {2}, degree = {3}, depth = {4}, height = {5}, {6}'.format(self.id, p, s, d, self.depth, h, typ)

def calc_cld_depth(nd):
    if nd.left:
        nd.left.depth = nd.depth + 1
        calc_cld_depth(nd.left)
    if nd.right:
        nd.right.depth = nd.depth + 1
        calc_cld_depth(nd.right)

n = int(input())
rbt = [Node(i) for i in range(n)]
for i in range(n):
    id,left,right = map(int, input().split())
    tgt = rbt[id]
    l,r = None,None
    if not left == -1:
        l = rbt[left]
        l.depth += tgt.depth + 1
        l.parent = tgt
        l.position = Node.left
        calc_cld_depth(l)
        tgt.left = l
    if not right == -1:
        r = rbt[right]
        r.depth += tgt.depth + 1
        r.parent = tgt
        r.position = Node.right
        calc_cld_depth(r)
        tgt.right = r
    if (not left == -1) and (not right == -1):
        l.sibling, r.sibling = r,l
    if left == -1 and right == -1:
        if tgt.parent: tgt.depth = tgt.parent.depth + 1

root = None
for c in rbt:
    if c.depth == 0: root = c
    h = 0
    if c.is_leaf():
        c.height = h
        p = c.parent
        while p:
            h += 1
            if p.height < h: p.height = h
            p = p.parent

from collections import deque

dq = deque()
visited = [None]*n
cnt = 0
dq.append(root)
while len(dq) > 0:
    pp = dq.pop()
    
    visited[cnt] = pp
    cnt += 1
    l,r = pp.left,pp.right
    if r: dq.append(r)
    if l: dq.append(l)
print('Preorder')
ss = ''
for v in visited: ss += ' '+str(v.id)
print(ss)


visited = [None]*n
cnt = 0
dq.append(root)
while len(dq):
    pp = dq.pop()
    
    dl = pp.num_child()
    if dl == 0:
        visited[cnt] = pp
        cnt += 1
        continue
    if dl > 0:
        l,r = pp.left,pp.right
        if l and l not in visited:
            dq.append(pp)
            dq.append(l)
        elif r:
            visited[cnt] = pp
            cnt += 1
            dq.append(r)
        else:
            visited[cnt] = pp
            cnt += 1
print('Inorder')
ss = ''
for v in visited: ss += ' '+str(v.id)
print(ss)


visited = [None]*n
cnt = 0
dq.append(root)
while len(dq) > 0:
    pp = dq.pop()
    
    dl = pp.num_child()
    if dl == 0:
        visited[cnt] = pp
        cnt += 1
        continue
    if dl > 0:
        l,r = pp.left, pp.right
        if (l and l not in visited) or (r and r not in visited):
            if pp: dq.append(pp)
            if r: dq.append(r)
            if l: dq.append(l)
        else:
            visited[cnt] = pp
            cnt += 1
            continue
print('Postorder')
ss = ''
for v in visited: ss += ' '+str(v.id)
print(ss)