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:
import sys

I = 0
L = 1
R = 2
P = 3
B = 4
D = 5
H = 6

def getroot(A, id):
    if A[id][P] > -1:
        return getroot(A,A[id][P])
    return A[id][I]

def preorder(N,id,A):
    if id < 0:
        return
    A.append(id)
    preorder(N,N[id][L],A)
    preorder(N,N[id][R],A)

def inorder(N,id,A):
    if id < 0:
        return
    inorder(N,N[id][L],A)
    A.append(id)
    inorder(N,N[id][R],A)

def postorder(N,id,A):
    if id < 0:
        return
    postorder(N,N[id][L],A)
    postorder(N,N[id][R],A)
    A.append(id)


def main():

    """ ????????? """
    num = int(input().strip())
    istr = sys.stdin.read()
    nlist = list(istr.splitlines())
    
    nodes = [[i, -1, -1, -1, -1, 0, 0] for i in range(num)]

    for nstr in nlist:
        i = list(map(int,nstr.split()))
        n = nodes[i[I]]
        n[I] = i[I]
        if i[L] > -1:
            n[L] = i[L]
            nodes[n[L]][P] = i[I]
            nodes[n[L]][B] = i[R]
        if i[R] > -1:
            n[R] = i[R]
            nodes[n[R]][P] = i[I]
            nodes[n[R]][B] = i[L]
#        print("set n:{} {} {}".format(n[I],n,i))

    r = getroot(nodes, 0)
#    setd(nodes,r, 0)

    pre = [""]
    ino = [""]
    pos = [""]

    preorder(nodes,r,pre)
    inorder(nodes,r,ino)
    postorder(nodes,r,pos)

    print("Preorder")
    print(" ".join(map(str,pre)))
    print("Inorder")
    print(" ".join(map(str,ino)))
    print("Postorder")
    print(" ".join(map(str,pos)))
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
class Node():
    def __init__(self, id, left, right, parent=-1, degree=-1, type=None):
        self.id = id
        self.left = left
        self.right = right
        self.parent = parent
        self.degree = degree
        self.type = type
        
    def show(self):
        print 'node %d: parent = %d, degree = %d, %s' % (self.id, self.parent, self.degree, self.type)

class Stack():
    def __init__(self):
        self.el = []
    def add(self, el):
        self.el.append(el)
    def pop(self):
        return self.el.pop()
        
def hasChild(x):
    if x == -1:
        return 0
    return 1


### input ###
dict = {}
a = []
n = int(raw_input())
for i in range(n):
    tmp = map(int, raw_input().split())
    dict[tmp[0]] = Node(tmp[0], tmp[1], tmp[2], degree=hasChild(tmp[1]) + hasChild(tmp[2]))

for i in range(n):
    a.append(dict[i])

for i in range(n):
    if not a[i].degree:
        continue
    a[a[i].left].parent = a[i].id
    a[a[i].right].parent = a[i].id

rootId = -1
for i in range(n):
    if a[i].parent != -1 and a[i].degree == 0:
        a[i].type = 'leaf'
    elif a[i].parent != -1 and a[i].degree > 0:
        a[i].type = 'internal node'
    else:
        a[i].type = 'root'
        rootId = a[i].id

### preorder ###
print 'Preorder'
pos = rootId
st = Stack()
ans = []
while True:
    ans.append(pos)
    if len(ans) == n:
        break
    if a[pos].degree > 0:
        if a[pos].left != -1 and a[pos].right != -1:
            st.add(a[pos].right)
        if a[pos].left != -1:
            pos = a[pos].left
        elif a[pos].left == -1:
            pos = a[pos].right
    elif a[pos].degree == 0:
        pos = st.pop()
print '', ' '.join(map(str, ans))

### inorder ###
print 'Inorder'
pos = rootId
st = Stack()
ans = []
while True:
    if a[pos].left != -1 and a[pos].left not in ans:
        if a[pos].right != -1:
            st.add(a[pos].right)
        st.add(pos)
        pos = a[pos].left
    elif a[pos].left == -1 and a[pos].right != -1 and a[pos].right not in ans:
        ans.append(pos)
        pos = a[pos].right
    else:
        ans.append(pos)
        if len(ans) == n:
            break
        pos = st.pop()    
print '', ' '.join(map(str, ans))

### postorder ###
print 'Postorder'
pos = rootId
st = Stack()
ans = []
while True:
    if a[pos].left != -1 and a[pos].left not in ans:
        st.add(pos)
        if a[pos].right != -1:
            st.add(a[pos].right)
        pos = a[pos].left
    elif a[pos].left == -1 and a[pos].right != -1 and a[pos].right not in ans:
        st.add(pos)
        pos = a[pos].right
    else:
        ans.append(pos)
        if len(ans) == n:
            break
        pos = st.pop()
print '', ' '.join(map(str, ans))

Submission status: Accepted

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[id].l = left
    nodes[id].r = right
    if left != -1:
        nodes[left].p = i
    if right != -1:
        nodes[right].p = i

def pre(node,path):
    path.append(node)
    if nodes[node].l != -1:
        pre(nodes[node].l,path)
    if nodes[node].r != -1:
        pre(nodes[node].r,path)

def ino(node,path):
    if nodes[node].l != -1:
        ino(nodes[node].l,path)
    path.append(node)
    if nodes[node].r != -1:
        ino(nodes[node].r,path)

def post(node,path):
    if nodes[node].l != -1:
        post(nodes[node].l,path)
    if nodes[node].r != -1:
        post(nodes[node].r,path)
    path.append(node)

for ind, n in enumerate(nodes):
    if n.p == None:
        root = ind
        break
print('Preorder')
l = []
pre(root, l)
print(' ' +  ' '.join(map(str, l)))
print('Inorder')
l = []
ino(root, l)
print(' ' +  ' '.join(map(str, l)))
print('Postorder')
l = []
post(root,l)
print(' ' + ' '.join(map(str, l)))

Submission status: Accepted

Solution code:
N = int(input())
tree = [None for _ in range(N)]
root = set(range(N))

for i in range(N):
    i, l, r = map(int,input().split())
    tree[i] = (l, r)
    root -= {l, r}

root_node = root.pop()

def preorder(i):
    if i == -1:
        return
    (l, r) = tree[i]
    print(" {}".format(i), end = "")
    preorder(l)
    preorder(r)
    
def inorder(i):
    if i == -1:
        return
    (l, r) = tree[i]
    inorder(l)
    print(" {}".format(i), end = "")
    inorder(r)
    
def postorder(i):
    if i == -1:
        return
    (l, r) = tree[i]
    postorder(l)
    postorder(r)
    print(" {}".format(i), end = "")
    
print('Preorder')
preorder(root_node)
print()

print('Inorder')
inorder(root_node)
print()

print('Postorder')
postorder(root_node)
print()

Submission status: Accepted

Solution code:
class Node:
    def __init__(self, node_id, left_child, right_child):
        self.node_id = node_id
        self.parent = -1
        self.sibling = -1
        self.degree = 0
        self.depth = 0
        self.height = 0
        self.node_type = ''

        self.left_child = left_child
        self.right_child = right_child
        

def binarytrees():
    def input_node_list():
        n = int(input())

        for i in range(n):
            node_id, left_child, right_child = list(map(int, input().split()))

            node = Node(node_id, left_child, right_child)
            node_list.append(node)

        node_list.sort(key = lambda node: node.node_id)

    def calc_parent_sibling_degree():
        if node.left_child != -1:
            node_list[node.left_child].parent = node.node_id
            node_list[node.left_child].sibling = node.right_child
            node.degree += 1

        if node.right_child != -1:
            node_list[node.right_child].parent = node.node_id
            node_list[node.right_child].sibling = node.left_child
            node.degree += 1

    def calc_depth(node_id):
        if  node_list[node_id].parent == -1:
            return 0
        else:
            return calc_depth(node_list[node_id].parent) + 1

    def calc_height(node_id):
        if node_list[node_id].degree == 0:
            return 0
        else:
            left_height = right_height = 0

            if node_list[node_id].left_child != -1:
                left_height = calc_height(node_list[node_id].left_child)
            if node_list[node_id].right_child != -1:
                right_height = calc_height(node_list[node_id].right_child)

            return max(left_height, right_height) + 1

    def calc_node_type():
        if node.depth == 0:
            node.node_type = 'root'
        elif node.height == 0:
            node.node_type = 'leaf'
        else:
            node.node_type = 'internal node'

    def show_node_info():
        print('node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'
            .format(node.node_id, node.parent, node.sibling,
            node.degree, node.depth, node.height, node.node_type))

    node_list = []
    input_node_list()

    for node in node_list:
        calc_parent_sibling_degree()

    # for node in node_list:
    #     node.depth = calc_depth(node.node_id)
    #     node.height = calc_height(node.node_id)

    #     calc_node_type()

    #     show_node_info()

    return node_list

def treewalk():
    def show_preorder(node_id):
        current_node = node_list[node_id]

        print(' {}'.format(current_node.node_id), end='')

        if current_node.left_child != -1:
            show_preorder(current_node.left_child)
        if current_node.right_child != -1:
            show_preorder(current_node.right_child)

    def show_inorder(node_id):
        current_node = node_list[node_id]

        if current_node.left_child != -1:
            show_inorder(current_node.left_child)

        print(' {}'.format(current_node.node_id), end='')

        if current_node.right_child != -1:
            show_inorder(current_node.right_child)

    def show_postorder(node_id):
        current_node = node_list[node_id]

        if current_node.left_child != -1:
            show_postorder(current_node.left_child)
        if current_node.right_child != -1:
            show_postorder(current_node.right_child)

        print(' {}'.format(current_node.node_id), end='')

    node_list = binarytrees()

    root_id = 0
    for node in node_list:
        if node.parent == -1:
            root_id = node.node_id
    
    print('Preorder')
    show_preorder(root_id)
    print('')

    print('Inorder')
    show_inorder(root_id)
    print('')

    print('Postorder')
    show_postorder(root_id)
    print('')

if __name__ == '__main__':
    treewalk()

Submission status: Accepted

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

    def pre_order_search(self):
        l = self.left
        r = self.right
        print(" " + str(self.node_id), end="")
        if l != -1:
            tree[l].pre_order_search()
        if r != -1:
            tree[r].pre_order_search()

    def in_order_search(self):
        l = self.left
        r = self.right
        if l != -1:
            tree[l].in_order_search()
        print(" " + str(self.node_id), end="")
        if r != -1:
            tree[r].in_order_search()

    def post_order_search(self):
        l = self.left
        r = self.right
        if l != -1:
            tree[l].post_order_search()
        if r != -1:
            tree[r].post_order_search()
        print(" " + str(self.node_id), end="")

n = int(input())
tree = [None for i in range(n)]
root_set = set(range(n))

for i in range(n):
    node_id, left, right = map(int, input().split())
    tree[node_id] = Node(node_id, left, right)
    root_set -= set([left, right])
root = root_set.pop()

print("Preorder")
tree[root].pre_order_search()
print()

print("Inorder")
tree[root].in_order_search()
print()

print("Postorder")
tree[root].post_order_search()
print()

Submission status: Accepted

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

    def pre_order_search(self):
        l = self.left
        r = self.right
        print("",self.node_id, end="")
        if l != -1:
            tree[l].pre_order_search()
        if r != -1:
            tree[r].pre_order_search()

    def in_order_search(self):
        l = self.left
        r = self.right
        if l != -1:
            tree[l].in_order_search()
        print("",self.node_id, end="")
        if r != -1:
            tree[r].in_order_search()

    def post_order_search(self):
        l = self.left
        r = self.right
        if l != -1:
            tree[l].post_order_search()
        if r != -1:
            tree[r].post_order_search()
        print("",self.node_id, end="")

n = int(input())
tree = [None for i in range(n)]
root_set = set(range(n))

for i in range(n):
    node_id, left, right = map(int, input().split())
    tree[node_id] = Node(node_id, left, right)
    root_set -= set([left, right])
root = root_set.pop()

print("Preorder")
tree[root].pre_order_search()
print()

print("Inorder")
tree[root].in_order_search()
print()

print("Postorder")
tree[root].post_order_search()
print()

Submission status: Accepted

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

    def pre_order_search(self):
        l = self.left
        r = self.right
        print("",self.node_id, end="")
        if l != -1:
            tree[l].pre_order_search()
        if r != -1:
            tree[r].pre_order_search()

    def in_order_search(self):
        l = self.left
        r = self.right
        if l != -1:
            tree[l].in_order_search()
        print("",self.node_id, end="")
        if r != -1:
            tree[r].in_order_search()

    def post_order_search(self):
        l = self.left
        r = self.right
        if l != -1:
            tree[l].post_order_search()
        if r != -1:
            tree[r].post_order_search()
        print("",self.node_id, end="")

n = int(input())
tree = [None for i in range(n)]
root_set = set(range(n))

for i in range(n):
    node_id, left, right = map(int, input().split())
    tree[node_id] = Node(node_id, left, right)
    root_set -= set([left, right])
root = root_set.pop()

print("Preorder")
tree[root].pre_order_search()
print("")

print("Inorder")
tree[root].in_order_search()
print()

print("Postorder")
tree[root].post_order_search()
print()

Submission status: Accepted

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

    def pre_order_search(self):
        l = self.left
        r = self.right
        print("",self.node_id, end="")
        if l != -1:
            tree[l].pre_order_search()
        if r != -1:
            tree[r].pre_order_search()

    def in_order_search(self):
        l = self.left
        r = self.right
        if l != -1:
            tree[l].in_order_search()
        print("",self.node_id, end="")
        if r != -1:
            tree[r].in_order_search()

    def post_order_search(self):
        l = self.left
        r = self.right
        if l != -1:
            tree[l].post_order_search()
        if r != -1:
            tree[r].post_order_search()
        print("",self.node_id, end="")

n = int(input())
tree = [None for i in range(n)]
root_set = set(range(n))

for i in range(n):
    node_id, left, right = map(int, input().split())
    tree[node_id] = Node(node_id, left, right)
    root_set -= set([left, right])
root = root_set.pop()

print("Preorder")
tree[root].pre_order_search()
print("")

print("Inorder")
tree[root].in_order_search()
print("")

print("Postorder")
tree[root].post_order_search()
print("")

Submission status: Accepted

Solution code:
from collections import defaultdict
def preorder(here, conn, chain):
    if here == -1:
        return
    chain.append(here)
    if conn[here]:
        preorder(conn[here][0], conn, chain)
        preorder(conn[here][1], conn, chain)

def inorder(here, conn, chain):
    if here == -1:
        return
    if conn[here]:
        inorder(conn[here][0], conn, chain)
        chain.append(here)
        inorder(conn[here][1], conn, chain)

def postorder(here, conn, chain):
    if here == -1:
        return
    if conn[here]:
        postorder(conn[here][0], conn, chain)
        postorder(conn[here][1], conn, chain)
    chain.append(here)

query = int(input())
connect = defaultdict(list)
in_v = [0 for n in range(query + 1)]
for _ in range(query):
    here, left, right = (int(n) for n in input().split(" "))
    connect[here] = [left, right]
    in_v[left] += 1
    in_v[right] += 1
for i in range(query):
    if not in_v[i]:
        root = i
        break
preo = []
ino = []
posto = []
preorder(root, connect, preo)
inorder(root, connect, ino)
postorder(root, connect, posto)

print("Preorder")
print("", end = " ")
print(*preo)
print("Inorder")
print("", end = " ")
print(*ino)
print("Postorder")
print("", end = " ")
print(*posto)

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:
n = int(input())
left = [None for i in range(n)]
right = [None 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(" {}".format(i), end = "")
    Preorder(left[i])
    Preorder(right[i])
      
def Inorder(i):
    if (i == -1):
        return
    Inorder(left[i])
    print(" {}".format(i), end = "")
    Inorder(right[i])
      
def Postorder(i):
    if (i == -1):
        return
    Postorder(left[i])
    Postorder(right[i])
    print(" {}".format(i), end = "")

print("Preorder")
Preorder(root)
print()
  
print("Inorder")
Inorder(root)
print()
  
print("Postorder")
Postorder(root)
print()

Submission status: Accepted

Solution code:
n = int(input())
left = [None for i in range(n)]
right = [None 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(" {}".format(i), end = "")
    Preorder(left[i])
    Preorder(right[i])

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

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

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

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

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

Submission status: Accepted

Solution code:
# -*- coding:utf-8 -*-
import sys


def tree_walk(tree, root):
    preorder_walk(tree, root)
    inorder_walk(tree, root)
    postoder_walk(tree, root)


def preorder_walk(tree, root):
    print("Preorder")
    result = []

    def preorder_walk_rec(node):
        if node == -1:
            pass
        else:
            result.append(str(node))
            preorder_walk_rec(tree[node][1])
            preorder_walk_rec(tree[node][2])

    preorder_walk_rec(root)
    print(" " + " ".join(result))


def inorder_walk(tree, root):
    print("Inorder")
    result = []

    def inorder_walk_rec(node):
        if node == -1:
            pass
        else:
            inorder_walk_rec(tree[node][1])
            result.append(str(node))
            inorder_walk_rec(tree[node][2])

    inorder_walk_rec(root)
    print(" " + " ".join(result))


def postoder_walk(tree, root):
    print("Postorder")
    result = []

    def postoder_work_rec(node):
        if node == -1:
            pass
        else:
            postoder_work_rec(tree[node][1])
            postoder_work_rec(tree[node][2])
            result.append(str(node))

    postoder_work_rec(root)
    print(" " + " ".join(result))


def get_tree():
    n = int(input())
    tree = [[-1, -1, -1] for x in range(0, n)]
    for node in sys.stdin.readlines():
        _id, left, right = [int(x) for x in node.split()]
        if left >= 0:
            tree[left][0] = _id
            tree[_id][1] = left
        if right >= 0:
            tree[right][0] = _id
            tree[_id][2] = right
    return tree


def get_root(tree):
    for i, node in enumerate(tree):
        if node[0] == -1:
            return i
    raise ValueError


if __name__ == "__main__":
    tree = get_tree()
    tree_walk(tree, get_root(tree))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

import sys
sys.setrecursionlimit(100000)

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

def preParse(u):
    if u == -1:
        return
    print(" " + str(u), end="")
    preParse(T[u].left)
    preParse(T[u].right)
    
def inParse(u):
    if u == -1:
        return
    inParse(T[u].left)
    print(" " + str(u), end="")
    inParse(T[u].right)
    
def postParse(u):
    if u == -1:
        return
    postParse(T[u].left)
    postParse(T[u].right)
    print(" " + str(u), end="")
    
    
if __name__ == '__main__':

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

    for _ in range(n):
        ID, left, right = list(map(int, input().split(" ")))
        T[ID].id = ID
        T[ID].left = left
        T[ID].right = right
        if left != -1:
            T[left].parent = ID
        if right != -1:
            T[right].parent = ID
    
    for node in T:
        if node.parent==-1:
            r = node.id
    
    print("Preorder")
    preParse(r)
    print()
        
    print("Inorder")
    inParse(r)
    print()
    
    print("Postorder")
    postParse(r)
    print()

Submission status: Accepted

Solution code:
class Tree:
    __slots__ = ['id', 'p', 'left', 'right', "type"]
    def __init__(self, id):
        self.id = id
        self.p = -1
        self.left = -1
        self.right = -1
        self.type = "leaf"
    def __str__(self):
        return f"node {self.id}: parent = {self.p}, left = {self.left}, right = {self.right}, type = {self.type}"
n = int(input())
tree = tuple(Tree(i) for i in range(n))
for _ in range(n):
    id, l, r = map(int, input().split())
    if l != -1:
        tree[id].left = l
        tree[l].p = id
    if r != -1:
        tree[id].right = r
        tree[r].p = id
root = 0
while tree[root].p != -1:
    root = tree[root].p
def preorder_tree_walk(id):
    print(f" {tree[id].id}", end="")
    if tree[id].left != -1:
        preorder_tree_walk(tree[id].left)
    if tree[id].right != -1:
        preorder_tree_walk(tree[id].right)
def inorder_tree_walk(id):
    if tree[id].left != -1:
        inorder_tree_walk(tree[id].left)
    print(f" {tree[id].id}", end="")
    if tree[id].right != -1:
        inorder_tree_walk(tree[id].right)
def postorder_tree_walk(id):
    if tree[id].left != -1:
        postorder_tree_walk(tree[id].left)
    if tree[id].right != -1:
        postorder_tree_walk(tree[id].right)
    print(f" {tree[id].id}", end="")
print("Preorder")
preorder_tree_walk(root)
print("\nInorder")
inorder_tree_walk(root)
print("\nPostorder")
postorder_tree_walk(root)
print()

Submission status: Accepted

Solution code:
import collections

nil = -1

def preParse(u):
    if u == nil:
        return None
    print(' {}'.format(u), end='')
    preParse(tree[u]['left'])
    preParse(tree[u]['right'])

def inParse(u):
    if u == nil:
        return None
    inParse(tree[u]['left'])
    print(' {}'.format(u), end='')
    inParse(tree[u]['right'])

def postParse(u):
    if u == nil:
        return None
    postParse(tree[u]['left'])
    postParse(tree[u]['right'])
    print(' {}'.format(u), end='')

if __name__ == '__main__':
    n = int(input())
    tree = collections.defaultdict(dict)
    roots = list()
    for _ in range(n):
        id_num, left, right = [int(x) for x in input().split()]
        tree[id_num]['left'] = left
        tree[id_num]['right'] = right
        if left != nil:
            tree[left]['parent'] = id_num
        if right != nil:
            tree[right]['parent'] = id_num
    
    for key, val in tree.items():
        if not 'parent' in tree[key]:
            roots.append(key)
    
    print('Preorder')
    preParse(roots[0])
    print()
    print('Inorder')
    inParse(roots[0])
    print()
    print('Postorder')
    postParse(roots[0])
    print()

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def p(u):
 if u+1:print(s,u,end=s);p(T[u]);p(T[u+N])
def i(u):
 if u+1:i(T[u]);print(s,u,end=s);i(T[u+N])
def o(u):
 if u+1:o(T[u]);o(T[u+N]);print(s,u,end=s)
s=''
N=int(input())
T=[0,0]*N
for _ in[0]*N:
 e=list(map(int,input().split()))
 T[e[0]],T[e[0]+N]=e[1:]
r=(set(range(N))-set(T)).pop()
print('Preorder');p(r)
print('\nInorder');i(r)
print('\nPostorder');o(r)
print()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# Tree Walk
class Tree:
    nodes = []
    def __init__(self):
        self.root = None
    def insert(self, nodenum, leftnum, rightnum):
        if leftnum != -1:
            self.nodes[nodenum].left = self.nodes[leftnum]
            self.nodes[leftnum].parent = self.nodes[nodenum]
        if rightnum != -1:
            self.nodes[nodenum].right = self.nodes[rightnum]
            self.nodes[rightnum].parent = self.nodes[nodenum]
    def preorder_walk(self, node):
        if node == -1:
            return
        print("", node.label, end = "")
        self.preorder_walk(node.left)
        self.preorder_walk(node.right)
    def inorder_walk(self, node):
        if node == -1:
            return
        self.inorder_walk(node.left)
        print("", node.label, end = "")
        self.inorder_walk(node.right)
    def postorder_walk(self, node):
        if node == -1:
            return
        self.postorder_walk(node.left)
        self.postorder_walk(node.right)
        print("", node.label, end = "")

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

tree = Tree()
n = int(input())
for i in range(n):
    tree.nodes.append(Node(i))
for i in range(n):
    num, left, right = map(int, input().split())
    tree.insert(num, left, right)
for i in tree.nodes:
    if i.parent == -1:
        print("Preorder")
        tree.preorder_walk(i)
        print("")
        print("Inorder")
        tree.inorder_walk(i)
        print("")
        print("Postorder")
        tree.postorder_walk(i)
        print("")