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:
NIL = -1
n = int(input())

class Node():
    def __init__(self):
        self.id = NIL
        self.left = NIL
        self.right = NIL
        self.parent = NIL
        
    def __str__(self):
        return "id : {}, left : {}, right : {}, parent : {}".format(self.id, self.left, self.right, self.parent)

tree = [Node() for i in range(n)]
for i in range(n):
    row = list(map(int,input().split()))
    tree[row[0]].id = row[0]
    tree[row[0]].left = row[1]
    tree[row[0]].right = row[2]
    
    if(row[1] != NIL):
        tree[row[1]].parent = row[0]
    if(row[2] != NIL):
        tree[row[2]].parent = row[0]


def preParse(u, res):
    if(u == NIL):
        return 
    res += [u]
    preParse(tree[u].left, res)
    preParse(tree[u].right, res)
    return res

def inParse(u, res):
    if(u == NIL):
        return
    inParse(tree[u].left, res)
    res += [u]
    inParse(tree[u].right, res)
    return res

def postParse(u, res):
    if(u == NIL):
        return
    postParse(tree[u].left, res)
    postParse(tree[u].right, res)
    res += [u]
    return res

for i in range(n):
    if(tree[i].parent == -1):
        print("Preorder")
        print(" {}".format(" ".join([str(ss) for ss in preParse(tree[i].id, [])])))
        
        print("Inorder")
        print(" {}".format(" ".join([str(ss) for ss in inParse(tree[i].id, [])])))
        
        print("Postorder")
        print(" {}".format(" ".join([str(ss) for ss in postParse(tree[i].id, [])])))
        
        break

Submission status: Accepted

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


nodeList=[]
preOrderList=[]
inOrderList=[]
postOrderList=[]

def readinput():
    global nodeList

    n=int(input())
    nodeList=[Node() for _ in range(n)]
    for _ in range(n):
        id,l,r=list(map(int,input().split()))
        nodeList[id].left=l
        nodeList[id].right=r
        if(l!=-1):
            nodeList[l].parent=id
        if(r!=-1):
            nodeList[r].parent=id
    
def findRoot():
    global nodeList

    for i,node in enumerate(nodeList):
        if node.parent==-1:
            return i
    return -1

def getPreOrder(id):
    global nodeList
    global preOrderList

    preOrderList.append(id)
    node=nodeList[id]
    if(node.left!=-1):
        getPreOrder(node.left)
    if(node.right!=-1):
        getPreOrder(node.right)

def getInOrder(id):
    global nodeList
    global inOrderList

    node=nodeList[id]
    if(node.left!=-1):
        getInOrder(node.left)
    inOrderList.append(id)
    if(node.right!=-1):
        getInOrder(node.right)
    
def getPostOrder(id):
    global nodeList
    global postOrderList

    node=nodeList[id]
    if(node.left!=-1):
        getPostOrder(node.left)
    if(node.right!=-1):
        getPostOrder(node.right)
    postOrderList.append(id)

def main():
    global nodeList

    root=findRoot()
    getPreOrder(root)
    getInOrder(root)
    getPostOrder(root)
    print('Preorder')
    print(' ',end='');print(' '.join(map(str,preOrderList)))
    print('Inorder')
    print(' ',end='');print(' '.join(map(str,inOrderList)))
    print('Postorder')
    print(' ',end='');print(' '.join(map(str,postOrderList)))

if __name__=='__main__':
    readinput()
    main()

Submission status: Accepted

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

def preorder(idx, nodelist):
    nodelist.append(idx)
    left, right = leftlist[idx], rightlist[idx]
    if left != -1:
        preorder(left, nodelist)
    if right != -1:
        preorder(right, nodelist)
    return nodelist

def inorder(idx, nodelist):
    left, right = leftlist[idx], rightlist[idx]
    if left != -1:
        inorder(left, nodelist)
    if right != -1:
        nodelist.append(idx)
        inorder(right, nodelist)
    else:
        nodelist.append(idx)
    return nodelist
    
def postorder(idx, nodelist):
    left, right = leftlist[idx], rightlist[idx]
    if left != -1:
        postorder(left, nodelist)
    if right != -1:
        postorder(right, nodelist)
        nodelist.append(idx)
    else:
        nodelist.append(idx)
    return nodelist

n = int(input())
parentlist = [-1]*n
leftlist = [-1]*n
rightlist = [-1]*n
for i in range(n):
    idx, left, right = map(int, input().split())
    leftlist[idx], rightlist[idx] = left, right
    if left != -1:
        parentlist[left] = idx
    if right != -1:
        parentlist[right] = idx
root = parentlist.index(-1)

print('Preorder\n', *preorder(root, []))
print('Inorder\n', *inorder(root, []))
print('Postorder\n', *postorder(root, []))

Submission status: Accepted

Solution code:



MAX = 10000
NIL = -1

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

# 先行順巡回
def preParse(u):
    if u == NIL: return
    print(" %d" % u ,end="")
    preParse(T[u].left)
    preParse(T[u].right)

# 中間順巡回
def inParse(u):
    if u == NIL: return
    inParse(T[u].left)
    print(" %d" % u ,end="")
    inParse(T[u].right)
# 後行順巡回
def postParse(u):
    if u == NIL: return
    postParse(T[u].left)
    postParse(T[u].right)
    print(" %d" % u ,end="")

n = int(input())

T = []
# n個のノードを用意
for i in range(n):
    node = Node()
    T.append(node)




for i in range(n):
    v,l,r = map(int,input().split())
    T[v].left = l
    T[v].right = r
    if l != NIL:
        T[l].parent = v
    if r != NIL:
        T[r].parent = v


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

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

def preorder_walk(i, tree_list):
    if i == -1:
        return
    print(' {}'.format(i),end='')
    preorder_walk(tree_list[i].left,tree_list)
    preorder_walk(tree_list[i].right,tree_list)

def inorder_walk(i, tree_list):
    if i == -1:
        return
    inorder_walk(tree_list[i].left,tree_list)
    print(' {}'.format(i),end='')
    inorder_walk(tree_list[i].right,tree_list)

def postorder_walk(i, tree_list):
    if i == -1:
        return
    postorder_walk(tree_list[i].left,tree_list)
    postorder_walk(tree_list[i].right,tree_list)
    print(' {}'.format(i),end='')

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

    tree_list = [Node(-1,-1,-1) for m in range(n)]
    for i in range(n):
        l = input().split()
        v = int(l[0])
        c_list = [int(l[m]) for m in range(1,len(l))]
        tree_list[v].left = c_list[0]
        tree_list[v].right = c_list[1]
        if c_list[0] != -1:
            tree_list[c_list[0]].parent = v
        if c_list[1] != -1:
            tree_list[c_list[1]].parent = v

    root = -1
    for i,t in enumerate(tree_list):
        if t.parent == -1:
            root = i
            break

    print('Preorder')
    preorder_walk(root,tree_list)
    print()
    print('Inorder')
    inorder_walk(root,tree_list)
    print()
    print('Postorder')
    postorder_walk(root,tree_list)
    print()

Submission status: Accepted

Solution code:
N = int(input())
left  =  [-1 for i in range(N)]
right =  [-1 for i in range(N)]
root = sum(range(N)) - N - 1
 
for i in range(N):
    i, l, r = map(int, input().split())
    left[i] = l
    right[i] = r
    root -= (l + r)
 
def preorder(i):
    if i == -1:
        return
    print(' ', i, sep = '', end = '')
    preorder(left[i])
    preorder(right[i])
     
def inorder(i):
    if i == -1:
        return
    inorder(left[i])
    print(' ', i, sep = '', end = '')
    inorder(right[i])
     
def postorder(i):
    if i == -1:
        return
    postorder(left[i])
    postorder(right[i])
    print(' ', i, sep = '', end = '')
     
print('Preorder')
preorder(root)
print()
 
print('Inorder')
inorder(root)
print()
 
print('Postorder')
postorder(root)
print()

Submission status: Accepted

Solution code:
def getroot():
    return [key for key,node in nodes.items() if node[0] == -1][0]

def Preorder(id):
    yield id
    for child_id in (child_id for child_id in nodes[id][1:] if child_id != -1):
        yield from Preorder(child_id)

def Inorder(id):
    if nodes[id][1] != -1:
        yield from Inorder(nodes[id][1])
    yield id
    if nodes[id][2] != -1:
        yield from Inorder(nodes[id][2])

def Postorder(id):
    for child_id in (child_id for child_id in nodes[id][1:] if child_id != -1):
        yield from Postorder(child_id)
    yield id

nodes = dict()
n = int(input())
for _ in range(n):
    id,l,r = list(map(int, input().split()))
    if id not in nodes:
        nodes[id] = (-1, -1, -1)
    node = nodes[id]
    node = (node[0], l, r)
    nodes[id] = node
    for child_id in [child_id for child_id in node[1:] if child_id != -1]:
        if child_id not in nodes:
            nodes[child_id] = (-1, -1, -1)
        child_node = nodes[child_id]
        child_node = (id, child_node[1], child_node[2])
        nodes[child_id] = child_node

rootid = getroot()
print("Preorder")
print(" ", end="")
print(*Preorder(rootid))
print("Inorder")
print(" ", end="")
print(*Inorder(rootid))
print("Postorder")
print(" ", end="")
print(*Postorder(rootid))

Submission status: Accepted

Solution code:
class binarytree:
    def __init__(self, num_parts, parts):
        self.num_parts = num_parts
        self.nodes = [None]*self.num_parts
        self.root = 0
        self.pre_order = []
        self.in_order = []
        self.post_order = []
        
        for i in range(self.num_parts):
            self.nodes[parts[i][0]] = binarynode(parts[i][0],parts[i][1],parts[i][2])

    def set_families(self):
        for i in range(self.num_parts):
            if self.nodes[i].left != -1:
                self.nodes[self.nodes[i].left].set_parent(i)
                self.nodes[self.nodes[i].left].set_sibling(self.nodes[i].right)
            if self.nodes[i].right != -1:
                self.nodes[self.nodes[i].right].set_parent(i)
                self.nodes[self.nodes[i].right].set_sibling(self.nodes[i].left)
        for i in range(self.num_parts):
            if self.nodes[i].parent == -1:
                self.root = i
            
    def set_type(self):
        for i in range(self.num_parts):
            self.nodes[i].check_type()

    def set_depth(self, pos, depth):
        self.nodes[pos].set_depth(depth)
        if self.nodes[pos].left != -1:
            self.set_depth(self.nodes[pos].left, depth+1)
        if self.nodes[pos].right != -1:
            self.set_depth(self.nodes[pos].right, depth+1)

    def set_height(self, pos, height):
        self.nodes[pos].set_height(height)
        if self.nodes[pos].parent != -1:
            self.set_height(self.nodes[pos].parent, height+1)
        return

    def preorder(self,pos):
        if len(self.pre_order) == self.num_parts:
            return
        if not pos in self.pre_order:
            self.pre_order.append(pos)
        if self.nodes[pos].left != -1 and not self.nodes[pos].left in self.pre_order:
            self.preorder(self.nodes[pos].left)
        elif self.nodes[pos].right != -1 and not self.nodes[pos].right in self.pre_order:
            self.preorder(self.nodes[pos].right)
        else:
            self.preorder(self.nodes[pos].parent)

    def inorder(self,pos):
        if len(self.in_order) == self.num_parts:
            return
        if self.nodes[pos].left != -1 and not self.nodes[pos].left in self.in_order:
            self.inorder(self.nodes[pos].left)
        elif not pos in self.in_order:
            self.in_order.append(pos)
            self.inorder(pos)
        elif self.nodes[pos].right != -1 and not self.nodes[pos].right in self.in_order:
            self.inorder(self.nodes[pos].right)
        else:
            self.inorder(self.nodes[pos].parent)

    def postorder(self,pos):
        if len(self.post_order) == self.num_parts:
            return
        if self.nodes[pos].left != -1 and not self.nodes[pos].left in self.post_order:
            self.postorder(self.nodes[pos].left)
        elif self.nodes[pos].right != -1 and not self.nodes[pos].right in self.post_order:
            self.postorder(self.nodes[pos].right)
        elif not pos in self.post_order:
            self.post_order.append(pos)
            self.postorder(pos)
        else:
            self.postorder(self.nodes[pos].parent)
            
    
class binarynode:
    def __init__(self, id, left, right):
        self.id = id
        self.parent = -1
        self.left = left
        self.right = right
        self.sibling = -1
        self.degree = 2
        self.depth = 0
        self.height = 0
        self.type = "internal node"

        if self.left == -1:
            self.degree -= 1
        if self.right == -1:
            self.degree -= 1
        
    def set_parent(self,parent):
        self.parent = parent
        return
    def set_sibling(self,sibling):
        self.sibling = sibling
        return
        
    def check_type(self):
        if self.parent == -1:
            self.type = "root"
        elif self.left == -1 and self.right == -1:
            self.type = "leaf"
        else:
            self.type = "internal node"
        return
            
    def set_depth(self,depth):
        self.depth = depth
        return
    def set_height(self,height):
        self.height = max(self.height, height)
        return
        
n = int(input())
obj = []
for i in range(n):
    obj.append(list(map(int, input().split())))

new_tree = binarytree(n, obj)
new_tree.set_families()
new_tree.set_type()
new_tree.set_depth(new_tree.root, 0)
for i in range(n):
    if new_tree.nodes[i].type == "leaf":
        new_tree.set_height(i, 0)

new_tree.preorder(new_tree.root)
new_tree.inorder(new_tree.root)
new_tree.postorder(new_tree.root)

str_pre = list(map(str,new_tree.pre_order))
str_in = list(map(str,new_tree.in_order))
str_post = list(map(str,new_tree.post_order))

print("Preorder")
print(" " + " ".join(str_pre))
print("Inorder")
print(" " + " ".join(str_in))
print("Postorder")
print(" " + " ".join(str_post))

Submission status: Accepted

Solution code:
from sys import stdin
N=int(input())
nodes=[None]*N
class node_tree():
    def __init__(self,node):
        self.node=node
        self.left=None
        self.right=None
        self.brother=None
        self.up=None
for i in range(N):
    node,left,right = list(map(int, (stdin.readline().strip().split())))
    if nodes[node] is not None:
        parent=nodes[node]
    else:parent=node_tree(node)
    if left!=-1:
        if nodes[left] is not None:
            left_node=nodes[left]
        else:left_node=node_tree(left)
        parent.left=left_node
        left_node.up=parent

    if right!=-1:
        if nodes[right] is not None:
            right_node=nodes[right]
        else:right_node=node_tree(right)
        parent.right=right_node
        right_node.up=parent
    if left!=-1 and right!=-1:
        left_node.brother=right_node
        right_node.brother=left_node
    if left!=-1:
        nodes[left] = left_node
    if right!=-1:
        nodes[right] = right_node
    nodes[node]=parent

def search_root(u):
    if u.up!=None:
        return search_root(u.up)
    else:
        return u.node
oya=search_root(nodes[0])
print("Preorder")
def pre(u):
    print("",u.node,end="")
    if u.left is not None:
        pre(u.left)
    if u.right is not None:
        pre(u.right)
pre(nodes[oya])
print("\nInorder")
def ino(u):

    if u.left is not None:
        ino(u.left)
    print("",u.node,end="")
    if u.right is not None:
        ino(u.right)
ino(nodes[oya])
print("\nPostorder")
def pos(u):

    if u.left is not None:
        pos(u.left)
    if u.right is not None:
        pos(u.right)
    print("",u.node,end="")
pos(nodes[oya])
print()

Submission status: Accepted

Solution code:
n = int(input())

class Node:
    def __init__(self):
        self.parent_id = -1
        self.sib = -1
        self.left = -1
        self.right = -1
        self.deg = 0
        self.height = 0
        self.depth = 0
        self.children = []

def cal_depth (node,x):
    node.depth = x

    for children_id in node.children:
        cal_depth(nodes[children_id],x+1)

def cal_height(node):

    h1 = 0
    h2 = 0
    if node.left != -1:
       h1 = cal_height(nodes[node.left]) + 1
    if node.right != -1:
       h2 = cal_height(nodes[node.right]) +1

    node.height = max(h1,h2)

    return max(h1,h2)



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

for i in range(n):
    deg = 0
    table = list(map(int,input().split()))
    node_id = table[0]
    nodes[node_id].left = table[1]
    nodes[node_id].right = table[2]
    if table[1] == -1 and table[2] == -1:
        nodes[node_id].deg = 0
    elif table[1] == -1 or table[2] == -1:
        nodes[node_id].deg = 1
        if table[1] != -1:
            nodes[table[1]].parent_id = node_id
            nodes[node_id].children.append(table[1])
        else:
            nodes[table[2]].parent_id = node_id
            nodes[node_id].children.append(table[2])
    else:
        nodes[node_id].deg = 2
        nodes[table[1]].parent_id = node_id
        nodes[table[2]].parent_id = node_id
        nodes[table[1]].sib = table[2]
        nodes[table[2]].sib = table[1]
        nodes[node_id].children.append(table[1])
        nodes[node_id].children.append(table[2])

ino_list = []
def Ino(node_id):
    if nodes[node_id].left != -1 :
        Ino(nodes[node_id].left)
    ino_list.append(node_id)
    if nodes[node_id].right != -1:
        Ino(nodes[node_id].right)

post_list =[]

def pos(node_id):
    l = nodes[node_id].left
    r = nodes[node_id].right
    if l != -1:
        pos(l)
    if r != -1:
        pos(r)
    post_list.append(node_id)


pre_list = []
def pre(node_id):
    pre_list.append(node_id)
    left = nodes[node_id].left
    right = nodes[node_id].right

    if left != -1:
        pre(left)
    if right != -1:
        pre(right)

for i in range(n):
    if nodes[i].parent_id == -1:
        pre(i)
        Ino(i)
        pos(i)
        break

pre_list = list(map(str,pre_list))

post_list = list(map(str,post_list))

ino_list = list(map(str,ino_list))


print("Preorder")
print(" ",end="")
print(' '.join(pre_list))
print("Inorder")
print(" ",end="")
print(' '.join(ino_list))
print("Postorder")
print(" ",end="")
print(' '.join(post_list))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2 ** 20)

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

    def __repr__(self):
        return '<Node object: parent={}, left={}, right={}>' .format(self.parent, self.left, self.right)


n = int(input())
# initialize tree
T = [Node() for _ in range(n)]
for i in range(n):
    idx, left, right = map(int, input().split())
    T[idx].left = left
    T[idx].right = right

    # set children's parent if Node idx is not leaf
    if left != -1:
        T[left].parent = idx
    if right != -1:
        T[right].parent = idx


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

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

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


for i in range(n):
    if T[i].parent == -1:
        print('Preorder')
        preParse(i)
        print()
        print('Inorder')
        inParse(i)
        print()
        print('Postorder')
        postParse(i)
        print()
        break

Submission status: Accepted

Solution code:
n=int(input())
childs=[0]*n

for i in range(n):
    node=list(map(int,input().split()))
    childs[node[0]] = node[1:]

class BisectTree:
    def __init__(self,childs):
        self.n=len(childs) 
        self.left_child=[0]*self.n
        self.right_child=[0]*self.n
        self.parent=[-1]*self.n
        for i in range(self.n):
            self.left_child[i]=childs[i][0]
            self.right_child[i]=childs[i][1]
            if childs[i][0] != -1:
                self.parent[childs[i][0]]=i
            if childs[i][1] != -1:
                self.parent[childs[i][1]]=i
        self.root=self.parent.index(-1)

tree=BisectTree(childs)

def preorder(tree,node,ans):
    ans.append(node)
    left=tree.left_child[node]
    right=tree.right_child[node]
    if left != -1:
        preorder(tree,left,ans)
    if right != -1:
        preorder(tree,right,ans)

def inorder(tree,node,ans):
    left=tree.left_child[node]
    right=tree.right_child[node]
    if left != -1:
        inorder(tree,left,ans)
    ans.append(node)
    if right != -1:
        inorder(tree,right,ans)

def postorder(tree,node,ans):
    left=tree.left_child[node]
    right=tree.right_child[node]
    if left != -1:
        postorder(tree,left,ans)
    if right != -1:
        postorder(tree,right,ans)
    ans.append(node)
    

preorder_ans=[]
preorder(tree,tree.root,preorder_ans)
print("Preorder\n ",end="")
print(*preorder_ans)

inorder_ans=[]
inorder(tree,tree.root,inorder_ans)
print("Inorder\n ",end="")
print(*inorder_ans)

postorder_ans=[]
postorder(tree,tree.root,postorder_ans)
print("Postorder\n ",end="")
print(*postorder_ans)

Submission status: Accepted

Solution code:
n = int(input())
lson, rson = [-1]*n, [-1]*n
parent = [-1]*n
for i in range(n):
    id, ls, rs = map(int, input().split())
    lson[id], rson[id] = ls, rs
    if ls != -1:
        parent[ls] = id
    if rs != -1:
        parent[rs] = id
def pre_order(r):
    if r == -1: return
    print("", r, end = '')
    pre_order(lson[r])
    pre_order(rson[r])

def in_order(r):
    if r == -1: return
    in_order(lson[r])
    print("", r, end = '')
    in_order(rson[r])

def post_order(r):
    if r == -1: return
    post_order(lson[r])
    post_order(rson[r])
    print("", r, end = '')

for i in range(n):
    if parent[i] == -1:
        print("Preorder")
        pre_order(i)
        print("")
        print("Inorder")
        in_order(i)
        print("")
        print("Postorder")
        post_order(i)
        print("")

Submission status: Accepted

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

N = int(input())
T = [Node(None, None, None) for _ in range(N)]
for t in T:
    i, left, right = map(int, input().split())
    if left != -1:
        T[i].left = left
        T[left].parent = i
    if right != -1:
        T[i].right = right
        T[right].parent = i

def preorder(i):
    if i == None:
        return
    print(' {}'.format(i), end='')
    preorder(T[i].left)
    preorder(T[i].right)

def inorder(i):
    if i == None:
        return
    inorder(T[i].left)
    print(' {}'.format(i), end='')
    inorder(T[i].right)

def postorder(i):
    if i == None:
        return
    postorder(T[i].left)
    postorder(T[i].right)
    print(' {}'.format(i), end='')

root = 0
for i, t in enumerate(T):
    if t.parent == None:
        root = i

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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10000000)
rd = sys.stdin.buffer.read
rl = sys.stdin.buffer.readline
NIL = -1

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

n = int(input())
T = [Node(NIL, NIL, NIL) for _ in range(n)]
for _ in range(n):
    x, y, z = map(int ,input().split())
    T[x].left = y
    T[x].right = z
    if y != NIL:
        T[y].p = x
    if z != NIL:
        T[z].p = x

#rootを見つける
def searchRoot():
    for node_i in range(n):
        if T[node_i].p == NIL:
            return node_i

preorder_res = []
def preorder(node_i):
    if node_i == NIL:
        return
    preorder_res.append(node_i)
    preorder(T[node_i].left)
    preorder(T[node_i].right)

inorder_res = []
def inorder(node_i):
    if node_i == NIL:
        return
    inorder(T[node_i].left)
    inorder_res.append(node_i)
    inorder(T[node_i].right)

postorder_res = []
def postorder(node_i):
    if node_i == NIL:
        return
    postorder(T[node_i].left)
    postorder(T[node_i].right)
    postorder_res.append(node_i)

def outPut(s, array):
    n = len(array)
    print(s)
    res =' '
    for i in range(len(array)):
        if i==n-1:
            res += str(array[i])
        else:
            res += str(array[i])+' ' 
    print(res)


def main():
    s = ['Preorder', 'Inorder', 'Postorder']
    l = [preorder_res, inorder_res, postorder_res]
    root = searchRoot()
    preorder(root)
    inorder(root)
    postorder(root)

    for i, j in zip(s, l):
        outPut(i, j)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

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

def main():
    n = int(input())
    t = [Node() for _ in range(n)]
    for _ in range(n):
        a,b,c = map(int,input().split())
        t[a].left = b
        t[a].right = c
        if b!=-1:t[b].p = a
        if c!=-1:t[c].p = a

    def preorder(i):
        print (' %d'%i,end='')
        if t[i].left!=-1:preorder(t[i].left)
        if t[i].right!=-1:preorder(t[i].right)

    def inorder(i):
        if t[i].left!=-1:inorder(t[i].left)
        print (' %d'%i,end='')
        if t[i].right!=-1:inorder(t[i].right)

    def postorder(i):
        if t[i].left!=-1:postorder(t[i].left)
        if t[i].right!=-1:postorder(t[i].right)
        print (' %d'%i,end='')

    root = -1
    for i in range(n):
        if t[i].p==-1:root = i
    
    print ('Preorder')
    preorder(root)
    print ()

    print ('Inorder')
    inorder(root)
    print ()

    print ('Postorder')
    postorder(root)
    print ()




if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:


graph = [[1,2],[0],[0,3,4],[2,4,5],[2,3,6],[3],[4]]

sakigake = []
nakagake = []
atogake = []




def main():
    n = int(input())
    tree = [[] for i in range(n)]
    check = [False]*n
    for i in range(n):
        a,b,c = list(map(int,input().split()))
        if b != -1:tree[a].append(b)
        else:tree[a].append(-1)
        if c != -1:tree[a].append(c)
        else:tree[a].append(-1)
        check[b] = True;check[c] = True
    indes = 0
    for i in range(n):
        if check[i] == False:
            indes = i
            break
    dfs(indes,tree)
    print("Preorder",end = "\n")
    for i in sakigake:
        print("",i,end = "")
    print("\nInorder",end = "\n")
    for i in nakagake:
        print("",i,end = "")
    print("\nPostorder",end = "\n")
    for i in atogake:
        print("",i,end = "")
    print()
def dfs(v,tree):
    #print(tree)
    sakigake.append(v)
    if tree[v][0] != -1:dfs(tree[v][0],tree)
    nakagake.append(v)
    if tree[v][1] != -1:dfs(tree[v][1],tree)
    atogake.append(v)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2**20)
n = int(input())
NIL = -1
class node:
    def __init__(self,parent,left,right):
        self.parent = parent
        self.left = left
        self.right = right
T = [node(NIL,NIL,NIL) for _ in range(n)]
D = [0]*n
def setDepth(u,p):#uはノードの番号、pはノードpの深さ。
    if u == NIL:
        return
    D[u] = p      #uより下にあるノードの深さをDに保存し、かえす
    if T[u].left != NIL:
        setDepth(T[u].left,p+1)
    if T[u].right != NIL:
        setDepth(T[u].right,p+1)
    return D
H = [0]*n
def setHeight(u,H):
    hl = 0
    hr = 0
    if T[u].left != NIL:
        hl = 1 + setHeight(T[u].left,H)
    if T[u].right != NIL:
        hr = 1 + setHeight(T[u].right,H)
    ret = max(hl,hr)
    H[u] = ret
    return ret
def getDegree(u):
    cc = 0
    if T[i].left != NIL:
        cc += 1
    if T[i].right != NIL:
        cc += 1
    return cc
def getDepth(u):
    d = 0
    while T[u].parent != NIL:
        u = T[u].parent
        d += 1
    return d
def getBrother(u):
    if T[u].parent == NIL:
        return NIL
    elif T[T[u].parent].left == u:
        return T[T[u].parent].right
    elif T[T[u].parent].right == u:
        return T[T[u].parent].left
def printChildren(u):#番号uのノードの子供をlistでかえす
    child = []
    if T[u].left != NIL:
        child.append(T[u].left)
    if T[u].right != NIL:
        child.append(T[u].right)
    return child
def ppp():
	for i in range(n):
  		ccc = T[i]
  		print(i,ccc.parent,ccc.left,ccc.right)
def findroot(u): #根をみつける
    while T[u].parent != NIL:
        u = T[u].parent
    return u
#巡回
rl = []
def rootleft(u,rl): #どのパターンでもrootからスタート
    if u == NIL:
        return
    rl.append(u)
    rootleft(T[u].left,rl)
    rootleft(T[u].right,rl)
lro = []
def leftroot(u,lro):
    if u == NIL:
        return
    leftroot(T[u].left,lro)
    lro.append(u)
    leftroot(T[u].right,lro)
lri = []
def leftright(u,lri):
    if u == NIL:
        return
    leftright(T[u].left,lri)
    leftright(T[u].right,lri)
    lri.append(u)
#ここから入力
firstid = 0
for i in range(n):
    id,left,right = map(int,input().split())
    if n == 0:
        firstid = id
    if left != NIL:
        T[id].left = left
        T[left].parent = id
    if right != NIL:
        T[id].right = right
        T[right].parent = id
r = findroot(firstid)
D = setDepth(r,0)
setHeight(r,H)
leftright(r,lri)
leftroot(r,lro)
rootleft(r,rl)
s0 = " ".join(map(str,rl))
s1 = " ".join(map(str,lro))
s2 = " ".join(map(str,lri))
print("Preorder")
print(" "+s0)
print("Inorder")
print(" "+s1)
print("Postorder")
print(" "+s2)