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, parent=-1, left=-1, right=-1):
        self.parent = parent
        self.left = left
        self.right = right


def preParse(u):
    """先行順巡回"""
    if u == -1:
        return
    print(" {}".format(u), end="")
    preParse(Nodes[u].left)
    preParse(Nodes[u].right)


def inParse(u):
    """中間順巡回"""
    if u == -1:
        return
    inParse(Nodes[u].left)
    print(" {}".format(u), end="")
    inParse(Nodes[u].right)


def postParse(u):
    """後行順巡回"""
    if u == -1:
        return
    postParse(Nodes[u].left)
    postParse(Nodes[u].right)
    print(" {}".format(u), end="")


n = int(input())
Nodes = []
for i in range(n):
    Nodes.append(Node())

for i in range(n):
    tmp = [int(_) for _ in input().split()]
    Nodes[tmp[0]].left = tmp[1]
    Nodes[tmp[0]].right = tmp[2]
    if tmp[1] != -1:
        Nodes[tmp[1]].parent = tmp[0]
    if tmp[2] != -1:
        Nodes[tmp[2]].parent = tmp[0]

# for i in range(n):
#     print(i, Nodes[i].parent, Nodes[i].left, Nodes[i].right)
# exit()
# root = -11
for i in range(n):
    if Nodes[i].parent == -1:
        root = i
        break

print("Preorder")
preParse(root)
print("")
print("Inorder")
inParse(root)
print("")
print("Postorder")
postParse(root)
print("")

Submission status: Accepted

Solution code:
class node:
    def __init__(self,nodeid):
        self.parent = None
        self.parentid = -1
        self.c_leftid = -1
        self.c_left = None
        self.c_rightid = -1
        self.c_right = None
        self.nodeid = nodeid
        self.type = "root"
    def setLeftChild(self,cn):
        self.c_left = cn
        self.c_leftid = cn.nodeid
        cn.parent = self
        cn.parentid = self.nodeid
        cn.setNodeType()
        self.setNodeType()
        return
    def setRightChild(self,cn):
        self.c_right = cn
        self.c_rightid = cn.nodeid
        cn.parent = self
        cn.parentid = self.nodeid
        cn.setNodeType()
        self.setNodeType()
        return
    def getDepth(self):
        cnt = 0
        t = self
        while True:
            if (t.parentid == -1 ):
                break
            t = t.parent
            cnt = cnt + 1
        return cnt
    def setNodeType(self):
        if (self.getDepth() == 0):
            self.type = "root"
        else:
            if ( self.c_rightid == -1 and self.c_leftid == -1 ):
                self.type = "leaf"
            else:
                self.type = "internal node" 
    def getNodeType(self):
        return self.type
    def getSibling(self):
        if ( self.parentid == -1):
            return -1
        i = self.parent
        if ( i.c_rightid == self.nodeid ):
            return i.c_leftid
        elif ( i.c_leftid == self.nodeid):
            return i.c_rightid
    def getHeight(self):
        lcnt = 0
        rcnt = 0
        if (self.c_leftid == -1  and self.c_rightid == -1 ):
            return 0
        elif (self.c_rightid  == -1):
            lcnt = lcnt + self.c_left.getHeight() + 1
        elif (self.c_leftid  == -1):
            rcnt = rcnt + self.c_right.getHeight() + 1
        else:
            lcnt = lcnt + self.c_left.getHeight() + 1
            rcnt = rcnt + self.c_right.getHeight() + 1
        if (lcnt >= rcnt):
            return lcnt
        else:
            return rcnt
    def getDegree(self):
        cnt = 0
        if (self.c_leftid != -1):
            cnt += 1
        if (self.c_rightid != -1):
            cnt += 1
        return cnt
    def getPreorder(self,r1):
        r1.append(self.nodeid)
        if (self.c_leftid != -1):
            r1 = self.c_left.getPreorder(r1)
        if (self.c_rightid != -1):
            r1 = self.c_right.getPreorder(r1)
        return r1       
    def getInorder(self,r1):
        if (self.c_leftid != -1):
            r1 = self.c_left.getInorder(r1)
        r1.append(self.nodeid)
        if (self.c_rightid != -1):
            r1 = self.c_right.getInorder(r1)
        return r1       
    def getPostorder(self,r1):
        if (self.c_leftid != -1):
            r1 = self.c_left.getPostorder(r1)
        if (self.c_rightid != -1):
            r1 = self.c_right.getPostorder(r1)
        r1.append(self.nodeid)
        return r1       
    def getRoot(self):
        if (self.parentid == -1):
            return self
        return self.parent.getRoot()


    def showNode(self):
        i1 = self.nodeid
        i2 = self.parentid
        i3 = self.getSibling()
        i4 = self.getDegree()
        i5 = self.getDepth()
        i6 = self.getHeight()
        i7 = self.getNodeType()
        print ('node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'.format(i1,i2,i3,i4,i5,i6,i7))
        return

nl = []
n = int(input())
for i in range(0,n):
    nl.append(node(i))

for i in range(0,n):
    (a,b,c) = map(int,input().split())
    if (b != -1):
        nl[a].setLeftChild(nl[b])
    if (c != -1):
        nl[a].setRightChild(nl[c])

root = nl[0].getRoot()
r1 = []
r2 = []
r3 = []
r1 = root.getPreorder(r1)
r2 = root.getInorder(r2)
r3 = root.getPostorder(r3)

print ("Preorder")
print ('',' '.join(map(str,r1)))
print ("Inorder")
print ('',' '.join(map(str,r2)))
print ("Postorder")
print ('',' '.join(map(str,r3)))

Submission status: Accepted

Solution code:
class Node:
    def __init__(self, left, right):
        self.left_node_no = left
        self.right_node_no = right


def preorder_tree_walk(nodes, node_no, order):
    if node_no not in nodes:
        return
    order.append(node_no)
    preorder_tree_walk(nodes, nodes[node_no].left_node_no, order)
    preorder_tree_walk(nodes, nodes[node_no].right_node_no, order)
    return


def inorder_tree_walk(nodes, node_no, order):
    if node_no not in nodes:
        return
    inorder_tree_walk(nodes, nodes[node_no].left_node_no, order)
    order.append(node_no)
    inorder_tree_walk(nodes, nodes[node_no].right_node_no, order)
    return

def postorder_tree_walk(nodes, node_no, order):
    if node_no not in nodes:
        return
    postorder_tree_walk(nodes, nodes[node_no].left_node_no, order)
    postorder_tree_walk(nodes, nodes[node_no].right_node_no, order)
    order.append(node_no)
    return

def main():
    n = int(input())
    nodes = {}
    for i in range(n):
        node_no, left, right = [int(x) for x in input().split()]
        nodes[node_no] = Node(left, right)

    children = set([val.left_node_no for val in nodes.values()] + [val.right_node_no for val in nodes.values()])
    root_node_no = list(set(nodes.keys()) - children)[0]

    preorder = []
    preorder_tree_walk(nodes, root_node_no, preorder)
    print("Preorder")
    print(" " + " ".join(map(str, preorder)))

    inorder = []
    inorder_tree_walk(nodes, root_node_no, inorder)
    print("Inorder")
    print(" " + " ".join(map(str, inorder)))

    postorder = []
    postorder_tree_walk(nodes, root_node_no, postorder)
    print("Postorder")
    print(" " + " ".join(map(str, postorder)))
    return


main()

Submission status: Accepted

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



def Preorder(node,order):
    order.append(node.name)
    try:
        Preorder(node.left,order)
    except:
        pass
    try:
        Preorder(node.right,order)
    except:
        pass

def Inorder(node,order):
    try:
        Inorder(node.left,order)
        order.append(node.name)
    except:
        order.append(node.name)
    
    try:
        Inorder(node.right,order)
    except:
        pass

def Postorder(node,order):
    try:
        Postorder(node.left,order)
    except:
        pass
    try:
        Postorder(node.right,order)
    except:
        pass
    order.append(node.name)





n=int(input())
Tree=[]
for i in range(n):
    Tree.append(Node(i))


for loop in range(n):
    name,left,right=map(int,input().split())
    if(left!=-1):
        Tree[name].left=Tree[left]
        Tree[left].root=Tree[name]
    if(right!=-1):
        Tree[name].right=Tree[right]
        Tree[right].root=Tree[name]



for i in range(n):
    if(Tree[i].root is None):
        root=Tree[i]


p_order=[]
Preorder(root,p_order)

i_order=[]
Inorder(root,i_order)

po_order=[]
Postorder(root,po_order)

print("Preorder")
print("",end=" ")
print(" ".join(list(map(str,p_order))))

print("Inorder")
print("",end=" ")
print(" ".join(list(map(str,i_order))))

print("Postorder")
print("",end=" ")
print(" ".join(list(map(str,po_order))))

Submission status: Accepted

Solution code:
import sys

def walk_preorder(n):
    c = children[n]
    print(' {}'.format(n), end='')
    if c[0]>=0: walk_preorder(c[0])
    if c[1]>=0: walk_preorder(c[1])

def walk_inorder(n):
    c = children[n]
    if c[0]>=0: walk_inorder(c[0])
    print(' {}'.format(n), end='')
    if c[1]>=0: walk_inorder(c[1])

def walk_postorder(n):
    c = children[n]
    if c[0]>=0: walk_postorder(c[0])
    if c[1]>=0: walk_postorder(c[1])
    print(' {}'.format(n), end='')
    

n = int(sys.stdin.readline())
parent = [-1 for _ in range(n)]
children = [[] for _ in range(n)]
for _ in range(n):
    id, left, right = list(map(int, sys.stdin.readline().split()))
    children[id] = [left, right]
    if left>=0:  parent[left] = id
    if right>=0: parent[right] = id

root=parent.index(-1)
order=[]
print('Preorder')
walk_preorder(root)
print()
print('Inorder')
walk_inorder(root)
print()
print('Postorder')
walk_postorder(root)
print()

Submission status: Accepted

Solution code:
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])))

Submission status: Accepted

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

Submission status: Accepted

Solution code:

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#이런식으로 코드 짜니까 이문제가 왜 이런걸 물어보는건지 이해가 감... 대단하다
class Node():
    def __init__(self, parent = -1, left = -1, right = -1): ##초기값 설정
        self.parent = parent
        self.left = left
        self.right = right
##초기 Node()class는 parent,left,right모두 -1
n = int(input())
ns = [Node()for i in range(n)] ##ns[0~(n-1)]모두 Node class 인스턴스화
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):  ##여기서의 i는 root 
    print(" "+str(i), end ='')  ##preorder은 루트 쪽부터 print
    if (ns[i].left != -1):  ##left쪽으로 쭉감
        preorder(ns, ns[i].left) ##ns[i].left를 root로써 재귀함수!
    if (ns[i].right != -1):
        preorder(ns, ns[i].right) ##left다했으면 right으로도 똑같이 해줌

def inorder(ns, i):
    if (ns[i].left != -1):
        inorder(ns, ns[i].left)  ##inorder는 일단 재귀함수로 왼쪽 끝까지 감
    print(' ' + str(i), end = '') ##왼쪽 끝가지 간 후 print (더이상 왼쪽으로 갈 수 없을때 print)
    if (ns[i].right != -1):
        inorder(ns, ns[i].right)  ##left로 갈수없을때 실행됨 (오른쪽으로 한번)

def postorder(ns, i):
    if (ns[i].left != -1):
        postorder(ns, ns[i].left)  ##inorder는 일단 재귀함수로 왼쪽 끝까지 감
    if (ns[i].right != -1):
        postorder(ns, ns[i].right)  ##left로 갈수없을때 오른쪽으로 끝까지 감
    print(' ' + str(i), end = '')  ##더이상 갈 수 없을때 print

for i in range(n):
    if (ns[i].parent == -1): ##root를 찾아서 위의 세 함수에 대입하여 print
        print('Preorder')
        preorder(ns, i)
        print()
        print('Inorder')
        inorder(ns, i)
        print()
        print('Postorder')
        postorder(ns, i)
        print()
        break

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# Tree - Tree Walk
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
# calc height
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
#for v in rbt: print(v)
from collections import deque
# Preorder
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)

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

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

Submission status: Runtime Error

Solution code:
def s(x):
    print('',x,end='')
def p(u):
    if u+1:s(u);p(R[u]);p(L(u))
def i(u):
    if u+1:i(R(u));s(u);p(L(u))
def o(u):
    if u+1:o(R(u));o(L(u));s(u)
        
n = int(inpout())
R, L = [0]*n, [0]*n
for _ in range(n):
    a, b, c = map(int, input().split())
    R[a] = b
    L[a] = c
root = (set(range(n))-set(R)-set(L)).pop()
print(f'Preorder{p(r)}')
print(f'Inorder{i(r)}')
print(f'Postorder{o(r)}')

Submission status: Runtime Error

Solution code:
def s(x):
    print('',x,end='')
def p(u):
    if u+1:s(u);p(R[u]);p(L(u))
def i(u):
    if u+1:i(R(u));s(u);p(L(u))
def o(u):
    if u+1:o(R(u));o(L(u));s(u)
        
n = int(input())
R, L = [0]*n, [0]*n
for _ in range(n):
    a, b, c = map(int, input().split())
    R[a] = b
    L[a] = c
root = (set(range(n))-set(R)-set(L)).pop()
print(f'Preorder{p(r)}')
print(f'Inorder{i(r)}')
print(f'Postorder{o(r)}')

Submission status: Runtime Error

Solution code:
def s(x):
    print('',x,end='')
def p(u):
    if u+1:s(u);p(R[u]);p(L(u))
def i(u):
    if u+1:i(R(u));s(u);p(L(u))
def o(u):
    if u+1:o(R(u));o(L(u));s(u)
        
n = int(input())
R, L = [0]*n, [0]*n
for _ in range(n):
    a, b, c = map(int, input().split())
    R[a] = b
    L[a] = c
root = (set(range(n))-set(R)-set(L)).pop()
print(f'Preorder{p(root)}')
print(f'Inorder{i(root)}')
print(f'Postorder{o(root)}')

Submission status: Runtime Error

Solution code:
def s(x):
    print('',x,end='')
def p(u):
    if u+1:s(u);p(R[u]);p(R(u+n))
def i(u):
    if u+1:i(R(u));s(u);p(L(u))
def o(u):
    if u+1:o(R(u));o(L(u));s(u)
        
n = int(input())
R, L = [0]*2*n, [0]*n
for _ in range(n):
    a, b, c = map(int, input().split())
    R[a], R[a+n] = b,c
    L[a] = c
root = (set(range(n))-set(R)-set(L)).pop()
print('Preorder',end = '');p(root)
print('\nInorder',end = '');i(root)
print('\nPostorder',end='');o(root)
print()

Submission status: Runtime Error

Solution code:
import sys


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

    def __str__(self):
        return "parent = %s, left = %s, right = %s" % (self.parent, self.left, self.right)

    def __repr__(self):
        return self.__str__()


def preorder_traverse(node_list, current):
    print(" %d" % current, end="")
    node = node_list[current]
    if node.left != -1:
        preorder_traverse(node_list, node.left)
    if node.right != -1:
        preorder_traverse(node_list, node.right)


def inorder_traverse(node_list, current):
    node = node_list[current]
    if node.left != -1:
        inorder_traverse(node_list, node.left)
    print(" %d" % current, end="")
    if node.right != -1:
        inorder_traverse(node_list, node.right)


def postorder_traverse(node_list, current):
    node = node_list[current]
    if node.left != -1:
        postorder_traverse(node_list, node.left)
    if node.right != -1:
        postorder_traverse(node_list, node.right)
    print(" %d" % current, end="")


def main():
    lines = sys.stdin.readlines()
    num_of_nodes = int(lines[0])
    node_list = [Node() for _ in range(num_of_nodes)]

    # Set filiation
    for line in lines[1:]:
        node_id, left, right = [int(x) for x in line.strip().split(" ")]
        node_list[node_id].left = left
        node_list[node_id].right = right

        node_list[left].parent = node_id
        node_list[right].parent = node_id

    # Find root node id
    for node_id, node in enumerate(node_list):
        if node.parent == -1:
            root = node_id
            break

    print("Preorder")
    preorder_traverse(node_list, root)
    print("\nInorder")
    inorder_traverse(node_list, root)
    print("\nPostorder")
    postorder_traverse(node_list, root)
    print("")

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
n = int(input())
class Node(object):
    def __init__(self, p, l, r):
        self.p = p
        self.l = l
        self.r = r

nodes = [Node(None, None, None) for i in range(n)]

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

def pre(node):
    print(node, end=" ")
    if nodes[node].l != -1:
        pre(nodes[node].l)
    if nodes[node].r != -1:
        pre(nodes[node].r)

def ino(node):
    if nodes[node].l != -1:
        ino(nodes[node].l)
    print(node, end=" ")
    if nodes[node].r != -1:
        ino(nodes[node].r)

def post(node):
    if nodes[node].l != -1:
        post(nodes[node].l)
    if nodes[node].r != -1:
        post(nodes[node].r)
    print(node, end=" ")

for ind, n in enumerate(nodes):
    if n.p != -1:
        root = ind
        break

print('Preorder')
pre(root)
print('\n')
print('InOrder')
ino(root)
print('\n')
print('Postorder')
post(root)