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):
		self.p = self.l = self.r = -1

def pre_order(nodes, u):
	if u == -1: return
	print(' ' + str(u), end='')
	pre_order(nodes, nodes[u].l)
	pre_order(nodes, nodes[u].r)

def in_order(nodes, u):
	if u == -1: return
	in_order(nodes, nodes[u].l)
	print(' ' + str(u), end='')
	in_order(nodes, nodes[u].r)

def post_order(nodes, u):
	if u == -1: return
	post_order(nodes, nodes[u].l)
	post_order(nodes, nodes[u].r)
	print(' ' + str(u), end='')

n = int(input())
nodes = []
for i in range(n): nodes.append(Node())
for i in range(n):
	id, l, r = map(int, input().split())
	nodes[id].l = l
	nodes[id].r = r
	if l != -1: nodes[l].p = id
	if r != -1: nodes[r].p = id
for i in range(n):
	if nodes[i].p == -1:
		rootId = i
		break
print('Preorder')
pre_order(nodes, rootId)
print()
print('Inorder')
in_order(nodes, rootId)
print()
print('Postorder')
post_order(nodes, rootId)
print()

Submission status: Accepted

Solution code:
class Node:
	def __init__(self):
		self.p = self.l = self.r = -1

def pre_order(nodes, root_id):
	st = []
	st.append(root_id)
	while len(st) > 0:
		cur = st.pop()
		print(' ' + str(cur), end='')
		if nodes[cur].r != -1: st.append(nodes[cur].r)
		if nodes[cur].l != -1: st.append(nodes[cur].l)
	print()
	
def in_order(nodes, root_id):
	st = []
	cur = root_id
	while cur != -1 or len(st) > 0:
		if cur != -1:
			st.append(cur)
			cur = nodes[cur].l
		else:
			cur = st.pop()
			print(' ' + str(cur), end='')
			cur = nodes[cur].r
	print()
		
def post_order(nodes, root_id):
	st = []
	lastVisited = -1
	cur = root_id
	while cur != -1 or len(st) > 0:
		if cur != -1:
			st.append(cur)
			cur = nodes[cur].l
		else:
			peek_id = st[len(st) - 1]
			if nodes[peek_id].r != -1 and nodes[peek_id].r != lastVisited:
				cur = nodes[peek_id].r
			else:
				print(' ' + str(peek_id), end='')
				lastVisited = st.pop()
	print()

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

print('Preorder')
pre_order(nodes, root_id)
print('Inorder')
in_order(nodes, root_id)
print('Postorder')
post_order(nodes, root_id)

Submission status: Accepted

Solution code:
from sys import stdin

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

def print_nodes(nodes, n):
    A = []
    B = []
    C = []
    def walk_tree(nodes, u):
        if u == -1:
            return
        r = nodes[u].right
        l = nodes[u].left
        nonlocal A
        A.append(u)
        walk_tree(nodes, l)
        B.append(u)
        walk_tree(nodes, r)
        C.append(u)

    for i in range(n):
        if nodes[i].parent == None:
            walk_tree(nodes, i)
            print("Preorder", end="\n ")
            print(*A, sep=" ")
            print("Inorder", end="\n ")
            print(*B, sep=" ")
            print("Postorder", end="\n ")
            print(*C, sep=" ")

def read_binary_tree(nodes, n):
    for _ in range(n):
        i = [int(i) for i in stdin.readline().strip().split()]
        nodes[i[0]].left = i[1]
        nodes[i[0]].right = i[2]
        if i[1] != -1:
            nodes[i[1]].parent = i[0]
        if i[2] != -1:
            nodes[i[2]].parent = i[0]

n = int(input())
nodes = [Node() for _ in range(n)]
read_binary_tree(nodes, n)
print_nodes(nodes, n)

Submission status: Accepted

Solution code:
from sys import stdin

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

def print_nodes(nodes, n):
    A = []
    B = []
    C = []
    def walk_tree(nodes, u):
        if u == -1:
            return
        r = nodes[u].right
        l = nodes[u].left
        A.append(u)
        walk_tree(nodes, l)
        B.append(u)
        walk_tree(nodes, r)
        C.append(u)

    for i in range(n):
        if nodes[i].parent == None:
            walk_tree(nodes, i)
            print("Preorder", end="\n ")
            print(*A, sep=" ")
            print("Inorder", end="\n ")
            print(*B, sep=" ")
            print("Postorder", end="\n ")
            print(*C, sep=" ")

def read_binary_tree(nodes, n):
    for _ in range(n):
        i = [int(i) for i in stdin.readline().strip().split()]
        nodes[i[0]].left = i[1]
        nodes[i[0]].right = i[2]
        if i[1] != -1:
            nodes[i[1]].parent = i[0]
        if i[2] != -1:
            nodes[i[2]].parent = i[0]

n = int(input())
nodes = [Node() for _ in range(n)]
read_binary_tree(nodes, n)
print_nodes(nodes, n)

Submission status: Accepted

Solution code:
#! /usr/bin/env python3
# -*- coding: utf-8 -*-

from sys import stdin


class Node():
    NIL = -1

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


def read_nodes(T):
    for line in stdin:
        id, left, right = [int(x) for x in line.split()]
        T[id].left = left
        if left != Node.NIL:
            T[left].parent = id
        T[id].right = right
        if right != Node.NIL:
            T[right].parent = id


def root_of(T):
    return [u.parent for u in T].index(Node.NIL)


def walk_preorder(T):

    def rec(id):
        nonlocal T

        if id == Node.NIL:
            return
        print("", id, end="")
        rec(T[id].left)
        rec(T[id].right)

    print("Preorder")
    rec(root_of(T))
    print()


def walk_inorder(T):

    def rec(id):
        nonlocal T

        if id == Node.NIL:
            return
        rec(T[id].left)
        print("", id, end="")
        rec(T[id].right)

    print("Inorder")
    rec(root_of(T))
    print()


def walk_postorder(T):

    def rec(id):
        nonlocal T

        if id == Node.NIL:
            return
        rec(T[id].left)
        rec(T[id].right)
        print("", id, end="")

    print("Postorder")
    rec(root_of(T))
    print()


def main():
    n = int(stdin.readline())
    T = [Node() for _ in range(n)]

    read_nodes(T)
    walk_preorder(T)
    walk_inorder(T)
    walk_postorder(T)


main()

Submission status: Accepted

Solution code:
class Trees():
    def __init__(self):
        self.nodes = {}
    def add_nodes(self, id):
        if id not in self.nodes:
            self.nodes[id] = Node(id)
    def add_child(self, id, child_id1, child_id2):
        for child_id in [child_id1, child_id2]:
            if child_id != -1:
                self.add_nodes(child_id)
                self.nodes[id].add_child_id(self.nodes[child_id])
        if child_id1 != -1:
            self.nodes[child_id1].sibling = child_id2
        if child_id2 != -1:            
            self.nodes[child_id2].sibling = child_id1
        self.nodes[id].left = child_id1
        self.nodes[id].right = child_id2
    def setheight(self, id):
        h1, h2 = 0, 0
        if self.nodes[id].right != -1:
            h1 = self.setheight(self.nodes[id].right) + 1
        if self.nodes[id].left != -1:
            h2 = self.setheight(self.nodes[id].left) + 1
        self.nodes[id].height = max(h1, h2)
        return max(h1, h2)
    def preorder(self,u):
        if u == -1:
            return
        print(f' {u}', end='')
        self.preorder(self.nodes[u].left)
        self.preorder(self.nodes[u].right)

    def inorder(self,u):
        if u == -1:
            return
        self.inorder(self.nodes[u].left)
        print(f' {u}', end='')
        self.inorder(self.nodes[u].right)
    def postorder(self,u):
        if u == -1:
            return
        self.postorder(self.nodes[u].left)
        self.postorder(self.nodes[u].right)
        print(f' {u}', end='')
    
        

         
class Node():
    def __init__(self, id):
        self.node = id
        self.parent = None
        self.depth = 0
        self.nodetype = 'root'
        self.children = []
        self.sibling = -1
        self.degree = 0
        self.height = 0
        self.left = -1
        self.right = -1
     
    def add_child_id(self, child):
        child.parent = self
        self.children.append(child)
        child.update_depth()
        self.update_nodetype()
        child.update_nodetype()
        self.degree += 1
        
     
    def update_depth(self):
        depth = self.depth
        if self.parent:
            self.depth = self.parent.depth + 1
        if depth != self.depth:
            for child in self.children:
                child.update_depth()
 
     
    def update_nodetype(self):
        if self.depth == 0:
            self.nodetype = 'root'
        elif len(self.children) > 0:
            self.nodetype = 'internal node'
        else:
            self.nodetype = 'leaf'
            

     
    def __str__(self):
        parent = self.parent.node if self.parent else -1
        return 'node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'.format(
            self.node, parent, self.sibling, self.degree, self.depth, self.height, self.nodetype)
     
 
tree = Trees()
 
n = int(input())
top = [0 for _ in range(n)]
for i in range(n):
    a = list(map(int,input().split()))
    tree.add_nodes(a[0])
    tree.add_child(id=a[0], child_id1=a[1], child_id2=a[2])
    if a[1] != -1:
        top[a[1]] += 1
    if a[2] != -1:
        top[a[2]] += 1

for id in range(n):
    tree.setheight(id)
    
for i in range(n):
    if top[i] == 0:
        b = i
        break
        

print('Preorder')
tree.preorder(b)
print()
print('Inorder')
tree.inorder(b)
print()
print('Postorder')
tree.postorder(b)
print()

Submission status: Accepted

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);i(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('Preorder');p(root)
print('\nInorder');i(root)
print('\nPostorder');o(root)
print()

Submission status: Accepted

Solution code:
def Pre(i):
    if dali[i].node != -1:
        ret = dali[i].node
        dali[i].node = -1
        order.append(ret)
    if dali[i].left != -1:
        Pre(dali[i].left)
    if dali[i].right != -1:
        Pre(dali[i].right)
def Pre2(u):
    if u == -1:
        return 
    order.append(u)
    Pre2(dali[u].left)
    Pre2(dali[u].right)
def In(i):
    if dali2[i].left != -1:
        In(dali2[i].left)
    if dali2[i].node != -1:
        
        ret = dali2[i].node
        dali2[i].node = -1
        order.append(ret)
    if dali2[i].right != -1:
        In(dali2[i].right)
def In2(u):
    if u == -1:
        return 
    In2(dali2[u].left)
    
    order.append(u)
    In2(dali2[u].right)


def Postorder(u):
    if u == -1:
        return None
    Postorder(dali3[u].left)
    Postorder(dali3[u].right)
    order.append(dali3[u].node)
    dali3[u].node = -1



    
class BiTree():
    def __init__(self, node, left, right):
        self.node = node
        self.left = left
        self.right = right


def inputdata(i):
    node, left, right = list(map(int, input().split()))
    dali[node] = BiTree(node, left, right)
    dali2[node] = BiTree(node, left, right)
    dali3[node] = BiTree(node, left, right)
def getParent(i):
    for k in range(n):
        if(dali[k].right == dali[i].node) or (dali[k].left == dali[i].node):
            dali[i].parent = dali[k].node
            return dali[i].parent
    dali[i].parent = -1
def getParent3(i):
    for k in range(n):
        if(dali3[k].right == dali3[i].node) or (dali3[k].left == dali3[i].node):
            dali3[i].parent = dali3[k].node
            return dali3[i].parent
    dali3[i].parent = -1
# Getting Root
        

n = int(input())
dali = [0] * n
dali2 = [0] * n
dali3 = [0] * n
order = []
for i in range(n):
    inputdata(i)
    """
for i in range(n):
    Pre(dali[i].node)
"""
for i in range(n):
    for j in range(n):
        if i == dali[j].left or i == dali[j].right:
            break
    if j == n-1:
        root = i
        break


order = []
for i in range(n):
    getParent(dali2[i].node)
for i in range(n):
    getParent(dali[i].node)
for i in range(n):
    getParent3(dali3[i].node)
Pre2(root)
print("Preorder")
print(" ",end = "")
print(*order)
order = []

In2(root)
print("Inorder")
print(" ",end = "")
print(*order)

order = []
print("Postorder")
print(" ",end = "")
Postorder(root)
print(*order)

Submission status: Accepted

Solution code:
def Pre(i):
    if dali[i].node != -1:
        ret = dali[i].node
        dali[i].node = -1
        order.append(ret)
    if dali[i].left != -1:
        Pre(dali[i].left)
    if dali[i].right != -1:
        Pre(dali[i].right)
def Pre2(u):
    if u == -1:
        return 
    order.append(u)
    Pre2(dali[u].left)
    Pre2(dali[u].right)

def In2(u):
    if u == -1:
        return 
    In2(dali2[u].left)
    
    order.append(u)
    In2(dali2[u].right)


def Postorder(u):
    if u == -1:
        return None
    Postorder(dali3[u].left)
    Postorder(dali3[u].right)
    order.append(dali3[u].node)
    dali3[u].node = -1



    
class BiTree():
    def __init__(self, node, left, right):
        self.node = node
        self.left = left
        self.right = right


def inputdata(i):
    node, left, right = list(map(int, input().split()))
    dali[node] = BiTree(node, left, right)
    dali2[node] = BiTree(node, left, right)
    dali3[node] = BiTree(node, left, right)

# Getting Root
        

n = int(input())
dali = [0] * n
dali2 = [0] * n
dali3 = [0] * n
order = []
for i in range(n):
    inputdata(i)
    """
for i in range(n):
    Pre(dali[i].node)
"""
for i in range(n):
    for j in range(n):
        if i == dali[j].left or i == dali[j].right:
            break
    if j == n-1:
        root = i
        break


order = []
Pre2(root)
print("Preorder")
print(" ",end = "")
print(*order)
order = []

In2(root)
print("Inorder")
print(" ",end = "")
print(*order)

order = []
print("Postorder")
print(" ",end = "")
Postorder(root)
print(*order)

Submission status: Accepted

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

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

for i in range(n):
    id, left, right = list(map(int, input().split()))
    node = node_list[id]
    if left > -1:
        node_list[left].parent = node
        node.left = node_list[left]
    if right > -1:
        node_list[right].parent = node
        node.right = node_list[right]

root = None
for node in node_list:
    if node.parent is None:
        root = node
        break

def preorder(node):
    if node is None:
        return
    print(' ' + str(node.id), end='')
    preorder(node.left)
    preorder(node.right)

def inorder(node):
    if node is None:
        return
    inorder(node.left)
    print(' ' + str(node.id), end='')
    inorder(node.right)

def postorder(node):
    if node is None:
        return
    postorder(node.left)
    postorder(node.right)
    print(' ' + str(node.id), end='')

print('Preorder')
preorder(root)
print('')

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

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

Submission status: Accepted

Solution code:
c=set(range(input()))
l=sorted([map(int,raw_input().split()) for _ in c])
for i in l:c-=set(i[1:])
d=c.pop()
def f(n):return "" if n<0 else "".join([" "+str(n) if j<1 else f(l[n][j]) for j in a])
for i in range(3):
    a=[1,2]
    a[i:i]=[0]
    print ["Pre","In","Post"][i]+"order"
    print f(d)

Submission status: Accepted

Solution code:
class Tree():
    def __init__(self):
        self.nodes = {}
        self.nodes[-1] = None
    def add_node(self, id):
        if id not in self.nodes:
            self.nodes[id] = Node(id)        
    def add_child(self, parent_id, left_id, right_id):
        self.add_node(parent_id)
        self.add_node(left_id)
        self.add_node(right_id)
        self.nodes[parent_id].add_child(self.nodes[left_id], self.nodes[right_id])
    def root(self):
        for node in self.nodes.values():
            if node and node.nodetype() == 'root':
                return node
    
class Node():
    def __init__(self, id):
        self.id = id
        self.parent = self.left = self.right = None
        self.depth = self.height = 0

    def add_child(self, left, right):
        self.left = left
        self.right = right
        
        self.update_height()
        
        for child in self.children():
            child.parent = self
            child.update_depth()
    def update_height(self):
        if self.degree():
            self.height = max([child.height + 1 for child in self.children()])
            if self.parent:
                self.parent.update_height()
            
    def update_depth(self):
        self.depth = self.parent.depth + 1
        for child in self.children():
            child.update_depth()
                
    def nodetype(self):
        if self.parent:
            if self.degree():
                return 'internal node'
            else:
                return 'leaf'
        else:
            return 'root'
    def degree(self):
        return len(self.children())
    
    def children(self):
        return [child for child in [self.left, self.right] if child]
    
    def sibling(self):
        if self.parent and self.parent.degree() == 2:
            if self.parent.left == self:
                return self.parent.right.id
            else:
                return self.parent.left.id
        else:
            return -1

    def __str__(self):
        return 'node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'.format(
            self.id,
            self.parent.id if self.parent else - 1,
            self.sibling(),
            self.degree(),
            self.depth,
            self.height,
            self.nodetype())
    def walk(self, order):
        orders = {'Preorder':[self, self.left, self.right], 'Inorder':[self.left, self, self.right], 'Postorder':[self.left, self.right, self]}
        
        for node in orders[order]:
            if node == self:
                yield node
            elif node:
                for childnode in node.walk(order):
                    yield childnode
                
tree = Tree()

n = int(input())
for i in range(n):
    id, left, right = map(int, input().split())
    tree.add_child(id, left, right)
orders = ['Preorder', 'Inorder', 'Postorder']

for order in orders:
    print(order)
    print('',*[node.id for node in tree.root().walk(order)])

Submission status: Accepted

Solution code:
# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_7_C
# Tree Walk
# Result:
import sys

class Node(object):
    def __init__(self, id_):
        super(Node, self).__init__()
        self.id_ = id_
        self.parent = None
        self.left = None
        self.right = None

    def set_child(self, left, right):
        self.left = left
        self.right = right

    def set_parent(self, parent):
        assert self.parent == None
        self.parent = parent

    def __str__(self):
        str_ = '%d' % (self.id_)
        return str_

def preorder_walk(n):
    if n == None: return ''
    str_ = ' %d' % (n.id_)
    str_ += preorder_walk(n.left)
    str_ += preorder_walk(n.right)
    return str_

def inorder_walk(n):
    if n == None: return ''
    str_ = inorder_walk(n.left)
    str_ += ' %d' % (n.id_)
    str_ += inorder_walk(n.right)
    return str_

def postorder_walk(n):
    if n == None: return ''
    str_ = postorder_walk(n.left)
    str_ += postorder_walk(n.right)
    str_ += ' %d' % (n.id_)
    return str_

nnodes = int(sys.stdin.readline())
nodes = []
for i in range(0, nnodes):
    nodes.append(Node(i))

# set parent and child
for _ in range(0, nnodes):
    vals = sys.stdin.readline().rstrip().split(' ')
    node_id = int(vals[0])
    left_id_ = int(vals[1])
    right_id_ = int(vals[2])
    node = nodes[node_id]
    left_ = nodes[left_id_] if left_id_ != -1 else None
    right_ = nodes[right_id_] if right_id_ != -1 else None
    node.set_child(left_, right_)
    if left_ != None:
        left_.set_parent(node)
    if right_ != None:
        right_.set_parent(node)

root_id = 0
# find root
if nodes[root_id].parent != None:
    for node in nodes:
        if node.parent == None:
            root_id = node.id_
            break
    assert root_id != 0

print 'Preorder'
print preorder_walk(nodes[root_id])
print 'Inorder'
print inorder_walk(nodes[root_id])
print 'Postorder'
print postorder_walk(nodes[root_id])

Submission status: Accepted

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

        if left != -1:
            node_list[left].parent = node_id
        if right != -1:
            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: Accepted

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

def preorder_tree_walk(root):
    result = []
    result.append(root.id)
    if root.left != None:
        result.extend(preorder_tree_walk(root.left))
    if root.right != None:
        result.extend(preorder_tree_walk(root.right))
    return result

def inorder_tree_walk(root):
    result = []
    if root.left != None:
        result.extend(inorder_tree_walk(root.left))
    result.append(root.id)
    if root.right != None:
        result.extend(inorder_tree_walk(root.right))
    return result

def postorder_tree_walk(root):
    result = []
    if root.left != None:
        result.extend(postorder_tree_walk(root.left))
    if root.right != None:
        result.extend(postorder_tree_walk(root.right))
    result.append(root.id)
    return result

n = int(raw_input())
tree = [Node(i) for i in xrange(n)]
for i in xrange(n):
    line = map(int, raw_input().split())
    id, left_id, right_id = line[0], line[1], line[2]
    if left_id != -1:
        tree[id].left = tree[left_id]
        tree[left_id].parent = tree[id]
    if right_id != -1:
        tree[id].right = tree[right_id]
        tree[right_id].parent = tree[id]
    if left_id != -1 and right_id != -1:
        tree[left_id].sibling = tree[right_id]
        tree[right_id].sibling = tree[left_id]

# find root
root = None
for t in tree:
    if t.parent == None:
        root = t

print 'Preorder'
print ' ' + ' '.join(map(str, preorder_tree_walk(root)))
print 'Inorder'
print ' ' + ' '.join(map(str, inorder_tree_walk(root)))
print 'Postorder'
print ' ' + ' '.join(map(str, postorder_tree_walk(root)))

Submission status: Accepted

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

def preorder(u):
    print u,
    if tree[u].left != -1:
        preorder(tree[u].left)
    if tree[u].right != -1:
        preorder(tree[u].right)

def inorder(u):
    if tree[u].left != -1:
        inorder(tree[u].left)
    print u,
    if tree[u].right != -1:
        inorder(tree[u].right)

def postorder(u):
    if tree[u].left != -1:
        postorder(tree[u].left)
    if tree[u].right != -1:
        postorder(tree[u].right)
    print u,



n = int(raw_input().strip())
tree = {}
for i in range(n):
    nid, left, right = map(int, raw_input().strip().split(' '))
    if not nid in tree: tree[nid] = Node(-1,left,right)
    else:
        tree[nid].left = left
        tree[nid].right = right
    if not left == -1:
        if not left in tree: tree[left] = Node(nid,-1,-1)
        else: tree[left].parent = nid
    if not right == -1:
        if not right in tree: tree[right] = Node(nid,-1,-1)
        else: tree[right].parent = nid

r = -1
for i in range(len(tree)):
    if tree[i].parent == -1:
        r = i
        break


print "Preorder"
print "",
preorder(r)
print
print "Inorder"
print "",
inorder(r)
print
print "Postorder"
print "",
postorder(r)
print

Submission status: Accepted

Solution code:
n = int(input())
tree = [None] * n
root = set(range(n))


def preorder(i):
    if i == -1: return
    (l, r) = tree[i]
    yield i
    for v in preorder(l): yield v
    for v in preorder(r): yield v


def inorder(i):
    if i == -1: return
    (l, r) = tree[i]
    for v in inorder(l): yield v
    yield i
    for v in inorder(r): yield v


def postorder(i):
    if i == -1: return
    (l, r) = tree[i]
    for v in postorder(l): yield v
    for v in postorder(r): yield v
    yield i


while n:
    i, l, r = list(map(int, input().split()))
    tree[i] = (l, r)
    root -= {l, r}
    n -= 1

root_node = root.pop()

for name, func in (('Preorder', preorder), ('Inorder', inorder), ('Postorder', postorder)):
    print(name)
    print(' ', end='')
    print(*func(root_node))

Submission status: Accepted

Solution code:
n = int(raw_input())



FORMAT = ('node {0.id}: parent = {0.parent}, sibling = {0.sibling}, degree = {0.degree}, depth = {0.depth}, height = {0.height}, {0.type}').format

class Node:
    def __init__(self):
        self.id = -1
        self.parent = -1
        self.left = -1
        self.right = -1
        self.sibling = -1
        self.degree = 0
        self.depth = 0
        self.height = 0
        self.type = 'leaf' if self.height == 0 else 'internal node'
        
    def setType(self):
        if self.height == 0 and self.parent != -1:
            self.type = 'leaf'
        elif self.parent == -1:
            self.type = 'root'
        else:
            self.type = 'internal node'

    def __str__(self):
        return FORMAT(self)

def preParse(u):
    if u == -1:
        return
    print u,
    preParse(T[u].left)
    preParse(T[u].right)

def inParse(u):
    if u == -1:
        return
    inParse(T[u].left)
    print u,
    inParse(T[u].right)

def postParse(u):
    if u == -1:
        return
    postParse(T[u].left)
    postParse(T[u].right)
    print u,


T = [Node() for _ in xrange(n)]

for i in xrange(n):
    a = map(int, raw_input().split())
    u = a[0]
    l = a[1]
    r = a[2]
    T[u].id = u
    T[u].left = l  #set child
    T[u].right = r  #set child
    if l != -1 and r != -1:
        T[l].parent = u  #set parent
        T[r].parent = u  #set parent
    elif l != -1 and r == -1:
        T[l].parent = u  #set parent
    elif l == -1 and r != -1:
        T[r].parent = u  #set parent

    if l != -1 and r != -1:
        T[u].degree = 2
        T[l].sibling = r
        T[r].sibling = l
    elif l != -1 and r == -1:
        T[u].degree = 1
    elif  l == -1 and r != -1:
        T[u].degree = 1

N = 0
for i in xrange(n):
    if T[i].parent == -1:
        N = T[i].id

print 'Preorder'
print '',
preParse(N)
print 
print 'Inorder'
print '',
inParse(N)
print 
print 'Postorder'
print '',
postParse(N)
print