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: Wrong Answer

Solution code:

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


def preparse(u):
    if u == -1: return
    print(" ", end="")
    print(u, end="")
    preparse(trees[u].left)
    preparse(trees[u].right)


def inparse(u):
    if u == -1: return
    #???????????????????§????
    inparse(trees[u].left)
    #??¨???
    print(" ", end="")
    print(u, end="")
    #??????????§????
    inparse(trees[u].right)
    

def postparse(u):
    if u == -1: return
    #???????????????????§????
    postparse(trees[u].left)
    #??????????§????
    postparse(trees[u].right)
    #??¨???
    print(" ", end="")
    print(u, end="")


N = int(input())
# ?????????
trees = [Tree(-1,-1,-1) for i in range(N)]
for i in range(N):
    l = list(map(int, input().split()))
    no = l[0]
    left = l[1]
    right = l[2]
    trees[no].left = left
    trees[no].right = right
    if left != -1: trees[left].parent = no
    if right != -1: trees[right].parent = no

print("Preorder")
preparse(0)
print("")
print("Inorder")
inparse(0)
print("")
print("Postorder")
postparse(0)

Submission status: Wrong Answer

Solution code:
import sys

def walk(T, nid, order):
  if nid < 0: return
  lid, rid = T[nid]

  if order == "pre":
    sys.stdout.write(" " + str(nid))
    walk(T, lid, order)
    walk(T, rid, order)
  elif order == "in":
    walk(T, lid, order)
    sys.stdout.write(" " + str(nid))
    walk(T, rid, order)
  else:
    walk(T, lid, order)
    walk(T, rid, order)
    sys.stdout.write(" " + str(nid))

T = {}
for i in range(int(input())):
  nid, lid, rid = map(int, input().split())
  T[nid] = [lid, rid]

print("Preorder"),  walk(T, 0, "pre"),  print()
print("Inorder"),   walk(T, 0, "in"),   print()
print("Postorder"), walk(T, 0, "post"), print()

Submission status: Wrong Answer

Solution code:
NIL = -1


class Node:
    right = NIL
    left = NIL
    parent = NIL


def preParse(u, S):
    global T
    if u == NIL:
        return
    S.append(u)
    preParse(T[u].left, S)
    preParse(T[u].right, S)


def inParse(u, S):
    global T
    if u == NIL:
        return
    preParse(T[u].left, S)
    S.append(u)
    preParse(T[u].right, S)


def postParse(u, S):
    global T
    if u == NIL:
        return
    preParse(T[u].left, S)
    preParse(T[u].right, S)
    S.append(u)


if __name__ == "__main__":
    # ????????¨??????
    n = int(input())
    T, A, B, C = [], [], [], []
    root_num = NIL
    for i in range(n):
        T.append(Node())
    for i in range(n):
        id, r, l = map(int, input().split())
        T[id].right = r
        T[id].left = l
    for i in range(n):
        if T[i].right != NIL:
            T[T[i].right].parent = i
        if T[i].left != NIL:
            T[T[i].left].parent = i
    for i in range(n):
        if T[i].parent == NIL:
            root_num = i

    print("Preorder")
    preParse(root_num, A)
    print(" "+ " ".join(map(str, A)))
    print("Inorder")
    inParse(root_num, B)
    print(" " + " ".join(map(str, B)))
    print("Postorder")
    postParse(root_num, C)
    print(" " + " ".join(map(str, C)))

Submission status: Wrong Answer

Solution code:
NIL = -1


class Node:
    right = NIL
    left = NIL
    parent = NIL


def preParse(u, S):
    global T
    if u == NIL:
        return
    S.append(u)
    preParse(T[u].left, S)
    preParse(T[u].right, S)


def inParse(u, S):
    global T
    if u == NIL:
        return
    preParse(T[u].left, S)
    S.append(u)
    preParse(T[u].right, S)


def postParse(u, S):
    global T
    if u == NIL:
        return
    preParse(T[u].left, S)
    preParse(T[u].right, S)
    S.append(u)


if __name__ == "__main__":
    # ????????¨??????
    n = int(input())
    T, A, B, C = [], [], [], []
    root_num = NIL
    for i in range(n):
        T.append(Node())
    for i in range(n):
        id, l, r = map(int, input().split())
        T[id].right = r
        T[id].left = l
    for i in range(n):
        if T[i].right != NIL:
            T[T[i].right].parent = i
        if T[i].left != NIL:
            T[T[i].left].parent = i
    for i in range(n):
        if T[i].parent == NIL:
            root_num = i

    print("Preorder")
    preParse(root_num, A)
    print(" "+ " ".join(map(str, A)))
    print("Inorder")
    inParse(root_num, B)
    print(" " + " ".join(map(str, B)))
    print("Postorder")
    postParse(root_num, C)
    print(" " + " ".join(map(str, C)))

Submission status: Wrong Answer

Solution code:
NIL = -1


class Node:
    left = NIL
    right = NIL
    parent = NIL


def preParse(u):
    global T
    if u == NIL:
        return
    print(" " + str(u), end='')
    preParse(T[u].left)
    preParse(T[u].right)


def inParse(u):
    global T
    if u == NIL:
        return
    preParse(T[u].left)
    print(" " + str(u), end='')
    preParse(T[u].right)


def postParse(u):
    global T
    if u == NIL:
        return
    preParse(T[u].left)
    preParse(T[u].right)
    print(" " + str(u), end='')


if __name__ == "__main__":
    # ????????¨??????
    n = int(input())
    T = [Node() for i in range(n)]
    root_num = NIL
    for i in range(n):
        l = list(map(int, input().split()))
        no = l[0]
        left = l[1]
        right = l[2]
        T[no].left = left
        T[no].right = right
        if left != NIL: T[left].parent = no
        if right != NIL: T[right].parent = no
    for i in range(n):
        if T[i].parent == NIL:
            root_num = i

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

Submission status: Wrong Answer

Solution code:
# coding=utf-8

class Node:
    def __init__(self, ID, left, right):
        ### output information ###
        self.id = ID
        self.parent = -1 #initialize
        self.sibling = -1 #initialize
        self.degree = -1 #initialize
        self.depth = -1 #initialize
        self.height = -1 #initialize
        self.type = None #initialize

        ### other information ###
        self.left = left
        self.right = right

def calc_depth(i):
    global node_list

    if node_list[i].depth != -1:
        return node_list[i].depth

    depth = 0
    if node_list[i].parent != -1:
        depth = calc_depth(node_list[i].parent) + 1

    node_list[i].depth = depth
    return depth


def calc_height(i):
    global node_list

    if node_list[i].height != -1:
        return node_list[i].height

    h1 = h2 = 0
    if node_list[i].right != -1:
        h1 = calc_height(node_list[i].right) + 1
    if node_list[i].left != -1:
        h2 = calc_height(node_list[i].left) + 1

    height = max(h1, h2)
    node_list[i].height = height
    return height

def pre_order(node):
    global node_list
    if node == -1:
        return None
    print(node, end = " ")
    pre_order(node_list[node].left)
    pre_order(node_list[node].right)

def in_order(node):
    global node_list
    if node == -1:
        return None
    in_order(node_list[node].left)
    print(node, end = " ")
    in_order(node_list[node].right)

def post_order(node):
    global node_list
    if node == -1:
        return None
    post_order(node_list[node].left)
    post_order(node_list[node].right)
    print(node, end = " ")

n = int(input())
data = [tuple(map(int, input().split())) for x in range(n)]
node_list = []

for data_row in data:
    ID, left, right = data_row
    node = Node(ID, left, right)
    node_list.append(node)

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

for i, node in enumerate(node_list):
    left = node.left
    right = node.right
    degree = 0

    ### child information ###
    if left != -1:
        degree += 1
        node_list[left].parent = i
        node_list[left].sibling = right

    if right != -1:
        degree += 1
        node_list[right].parent = i
        node_list[right].sibling = left

    ### self information ###
    node.degree = degree

for i in range(n):
    calc_depth(i)
    calc_height(i)

    node = node_list[i]

    if node.depth == 0:
        node.type = 'root'
    elif node.height == 0:
        node.type = 'leaf'
    else:
        node.type = 'internal node'

    #print("node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}".format(node.id, node.parent, node.sibling, node.degree, node.depth, node.height, node.type))

print("Preorder")
pre_order(0)
print("\nInorder")
in_order(0)
print("\nPostorder")
post_order(0)
print()

Submission status: Wrong Answer

Solution code:
import sys

def main():
    n = input()
    tree = MyTree(n)
    for i in range(n):
        id_cn = map(int,raw_input().split())
        id_node = id_cn.pop(0)
        
        tree.add(id_node,None,id_cn)
    
    tree.search_children()
    tree.set_depth_height(tree.nodes[tree.id_root],0)

    print "Prorder"
    tree.preorder(tree.nodes[tree.id_root])
    print ""
    print "Inorder"
    tree.inorder(tree.nodes[tree.id_root])
    print ""
    print "Postorder"
    tree.postorder(tree.nodes[tree.id_root])

    
class MyTree():
    def __init__(self,num_nodes):
        self.nodes = [MyNode() for i in range(num_nodes)]
        self.id_root = None

    def add(self,id_node,id_parent,id_children):
        node = self.nodes[id_node]
        node.id_self = id_node
        node.id_parent = id_parent
        node.id_children = id_children
    
    def search_children(self):
        for node in self.nodes:
            if all(item==-1 for item in node.id_children):
                node.node_type = "leaf"
                node.degree = 0
            else:
                node.node_type = "internal node"
                l = node.id_children[0]
                r = node.id_children[1]
                if l == -1:
                    node.degree = 1
                    self.nodes[r].id_parent = node.id_self
                    self.nodes[r].sibling = l
                elif r == -1:
                    node.degree = 1
                    self.nodes[l].id_parent = node.id_self
                    self.nodes[l].sibling = r
                else:
                    node.degree = 2
                    self.nodes[l].id_parent = node.id_self
                    self.nodes[r].id_parent = node.id_self
                    self.nodes[l].sibling = r
                    self.nodes[r].sibling = l

        for node in self.nodes:
            if node.id_parent == None:
                node.id_parent = -1
                node.node_type = "root"
                self.id_root = node.id_self
                break

    def set_depth_height(self,node,depth):
        node.depth = depth
        l_height = []
        if all(item==-1 for item in node.id_children):
            node.height = 0
            return 0
        else:
            for item in node.id_children:
                if not item == -1:
                    l_height.append(self.set_depth_height(self.nodes[item],depth+1))
            height = max(l_height)+1
            node.height = height
            return height

    def preorder(self,node):
        sys.stdout.write(" {}".format(node.id_self))
        l,r = node.id_children
        if not l == -1:
            self.preorder(self.nodes[l])
        if not r == -1:
            self.preorder(self.nodes[r])    

    def inorder(self,node):
        l,r = node.id_children
        if not l == -1:
            self.inorder(self.nodes[l])
        sys.stdout.write(" {}".format(node.id_self))
        if not r == -1:
            self.inorder(self.nodes[r])

    def postorder(self,node):
        l,r = node.id_children
        if not l == -1:
            self.postorder(self.nodes[l])
        if not r == -1:
            self.postorder(self.nodes[r])
        sys.stdout.write(" {}".format(node.id_self))
                


class MyNode():
    def __init__(self):
        self.id_self = None
        self.id_parent = None
        self.id_children = None
        self.depth = None
        self.node_type = None
        self.n_children = 0
        self.sibling = -1
        self.degree = 0
        self.height = 0


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n = int(input())
tree = [0] * n
root = set(range(n))
for i in range(n):
    node_id, left, right = map(int, input().split())
    tree[node_id] = (left, right)
    root -= {left, right}
root_node = root.pop()


def preorder(i):
    if i == -1:
        return
    (left, right) = tree[i]
    yield i
    yield from preorder(left)
    yield from preorder(right)


def inorder(i):
    if i == -1:
        return
    (left, right) = tree[i]
    yield from inorder(left)
    yield i
    yield from inorder(right)


def postorder(i):
    if i == -1:
        return
    (left, right) = tree[i]
    yield from postorder(left)
    yield from postorder(right)
    yield i

print("preorder\n ", end="")
print(*preorder(root_node))
print("inorder\n ", end="")
print(*inorder(root_node))
print("postorder\n ", end="")
print(*postorder(root_node))

Submission status: Wrong Answer

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:
        st.add(a[pos].right)
        pos = a[pos].left
    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].degree > 0 and a[pos].left not in ans:
        st.add(a[pos].right)
        st.add(pos)
        pos = a[pos].left
    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].degree > 0 and a[pos].left not in ans:
        st.add(pos)
        st.add(a[pos].right)
        pos = a[pos].left
    else:
        ans.append(pos)
        if len(ans) == n:
            break
        pos = st.pop()
print '', ' '.join(map(str, ans))

Submission status: Wrong Answer

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(ans)
        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: Wrong Answer

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):
    print(node, end=" ")
    if nodes[node].l != -1:
        pre(nodes[node].l)
    if nodes[node].r != -1:
        pre(nodes[node].r)

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

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

for ind, n in enumerate(nodes):
    if n.p == None:
        root = ind
        break
print('Preorder')
pre(root)
print('\n')
print('InOrder')
ino(root)
print('\n')
print('Postorder')
post(root)

Submission status: Wrong Answer

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: Wrong Answer

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]
    inorder(l)
    inorder(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: Wrong Answer

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()
    
    print('Preorder')
    show_preorder(0)
    print('')

    print('Inorder')
    show_inorder(0)
    print('')

    print('Postorder')
    show_postorder(0)
    print('')

if __name__ == '__main__':
    treewalk()

Submission status: Wrong Answer

Solution code:
class Node:
    def __init__(self, nid):
        self.nid = nid
        self.l = None
        self.r = None

def preorder(T):
    ret = [T.nid]
    if T.l != None:
        ret += preorder(T.l)
    if T.r != None:
        ret += preorder(T.r)
    return ret

def inorder(T):
    ret = []
    if T.l != None:
        ret += inorder(T.l)
    ret.append(T.nid)
    if T.r != None:
        ret += inorder(T.r)
    return ret

def postorder(T):
    ret = []
    if T.l != None:
        ret += postorder(T.l)
    if T.r != None:
        ret += postorder(T.r)
    ret.append(T.nid)
    return ret



n = int(raw_input())
nodes = {}
for _ in range(n):
    nid, lid, rid = raw_input().split(' ')
    if not nid in nodes:
        node = Node(nid)
        nodes[nid] = node
    if lid != '-1':
        if not lid in nodes:
            l = Node(lid)
            nodes[lid] = l
        nodes[nid].l = nodes[lid]
    if rid != '-1':
        if not rid in nodes:
            r = Node(rid)
            nodes[rid] = r
        nodes[nid].r = nodes[rid]

T = nodes['0']

print "Preorder"
print ' '.join(preorder(T))
print "Inorder"
print ' '.join(inorder(T))
print "Postorder"
print ' '.join(postorder(T))

Submission status: Wrong Answer

Solution code:
class Node:
    def __init__(self, nid):
        self.nid = nid
        self.l = None
        self.r = None

def preorder(T):
    ret = [T.nid]
    if T.l != None:
        ret += preorder(T.l)
    if T.r != None:
        ret += preorder(T.r)
    return ret

def inorder(T):
    ret = []
    if T.l != None:
        ret += inorder(T.l)
    ret.append(T.nid)
    if T.r != None:
        ret += inorder(T.r)
    return ret

def postorder(T):
    ret = []
    if T.l != None:
        ret += postorder(T.l)
    if T.r != None:
        ret += postorder(T.r)
    ret.append(T.nid)
    return ret



n = int(raw_input())
nodes = {}
T = None
for _ in range(n):
    nid, lid, rid = raw_input().split(' ')
    if not nid in nodes:
        node = Node(nid)
        nodes[nid] = node
    if lid != '-1':
        if not lid in nodes:
            l = Node(lid)
            nodes[lid] = l
        nodes[nid].l = nodes[lid]
    if rid != '-1':
        if not rid in nodes:
            r = Node(rid)
            nodes[rid] = r
        nodes[nid].r = nodes[rid]
    if T == None:
        T = nodes[nid]

print "Preorder"
print '',
print ' '.join(preorder(T))
print "Inorder"
print '',
print ' '.join(inorder(T))
print "Postorder"
print '',
print ' '.join(postorder(T))

Submission status: Wrong Answer

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
        print(self.node_id, self.left, 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("")