Problem:

Rooted Trees

A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).

Fig. 1

A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."

Your task is to write a program which reports the following information for each node u of a given rooted tree T:

node ID of u

parent of u

depth of u

node type (root, internal node or leaf)

a list of chidlren of u

If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.

siblings.

-->

A node with no children is an external node or leaf. A nonleaf node is an internal node

The number of children of a node x in a rooted tree T is called the degree of x.

The length of the path from the root r to a node x is the depth of x in T.

Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.

Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.

Fig. 2

Input

The first line of the input includes an integer n, the number of nodes of the tree.

In the next n lines, the information of each node u is given in the following format:

id k c1 c2 ... ck

where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.

Output

Print the information of each node in the following format ordered by IDs:

node id: parent = p, depth = d, type, [c1...ck]

p is ID of its parent. If the node does not have a parent, print -1.

d is depth of the node.

type is a type of nodes represented by a string (root, internal node or leaf). If the root can be considered as a leaf or an internal node, print root.

c1...ck is the list of children as a ordered tree.

Please follow the format presented in a sample output below.

Constraints

1 ≤ n ≤ 100000

Sample Input 1

13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0

Sample Output 1

node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []

Sample Input 2

4
1 3 3 2 0
0 0
3 0
2 0

Sample Output 2

node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, []

Note

You can use a left-child, right-sibling representation to implement a tree which has the following data:

the parent of u

the leftmost child of u

the immediate right sibling of u

Template in C

-->

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.



Sample input:
13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0


Sample output:
node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []

Submission status: Runtime Error

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

    def get_depth(self):
        if self.parent == None:
            return 0
        else:
            depth = 1
            t = Nodes[self.parent]
            while t.parent != -1:
                t = Nodes[t.parent]
                depth += 1
            return depth

    def get_type(self):
        if self.parent == -1:
            return 'root'
        elif self.left == None:
            return 'leaf'
        else:
            return 'internal node'


def decode_node_data(n):
    global Nodes
    num_of_elem = len(n)
    if num_of_elem < 2:
        raise ValueError
    elif num_of_elem == 2:  # leaf
        pass
    else:
        id, num_of_children = int(n[0]), int(n[1])
        children = n[2:]
        Nodes[id].left = int(children[0])
        prev_child = None
        for c in children:
            Nodes[int(c)].parent = id
            if prev_child != None:
                Nodes[prev_child].right = int(c)
            prev_child = int(c)


MAX_NODES = 20
Nodes = [Node(-1, None, None) for _ in range(MAX_NODES)]
if __name__ == '__main__':
    # ??????????????\???
    num_of_nodes = int(input())
    node_data = []
    for _ in range(num_of_nodes):
        node_data.append(input().split(' '))

    # ??¨????§£???
    for n in node_data:
        decode_node_data(n)


    # ???????????¨???
    for node_id in range(num_of_nodes):
        type = Nodes[node_id].get_type()
        children = []
        if type != 'leaf':
            c = Nodes[node_id].left
            children.append(c)
            while Nodes[c].right != None:
                c = Nodes[c].right
                children.append(c)

        print('node {0}: parent = {1}, depth = {2}, {3}, [{4}]'.format(node_id, Nodes[node_id].parent, Nodes[node_id].get_depth(), type,
                                                                       ', '.join(map(str, children))))

Submission status: Runtime Error

Solution code:

class Node(object):
    def __init__(self, parent, left, right):
        self.parent = parent  # ????????????
        self.left = left      # ??????????????????????????????????????????
        self.right = right    # ??????????????????????????????????????´?????????

    def get_depth(self):
        if self.parent == -1:
            return 0
        else:
            depth = 1
            t = Nodes[self.parent]
            while t.parent != -1:
                t = Nodes[t.parent]
                depth += 1
            return depth

    def get_type(self):
        if self.parent == -1:
            return 'root'
        elif self.left == None:
            return 'leaf'
        else:
            return 'internal node'


def decode_node_data(n):
    global Nodes
    num_of_elem = len(n)
    if num_of_elem < 2:
        raise ValueError
    elif num_of_elem == 2:  # leaf
        pass
    else:
        id, num_of_children = int(n[0]), int(n[1])
        children = n[2:]
        Nodes[id].left = int(children[0])
        prev_child = None
        for c in children:
            Nodes[int(c)].parent = id
            if prev_child != None:
                Nodes[prev_child].right = int(c)
            prev_child = int(c)


MAX_NODES = 20
Nodes = [Node(-1, None, None) for _ in range(MAX_NODES)]
if __name__ == '__main__':
    # ??????????????\???
    num_of_nodes = int(input())
    node_data = []
    for _ in range(num_of_nodes):
        node_data.append(input().split(' '))

    # ??¨????§£???
    for n in node_data:
        decode_node_data(n)


    # ???????????¨???
    for node_id in range(num_of_nodes):
        type = Nodes[node_id].get_type()
        children = []
        if type != 'leaf':
            if Nodes[node_id].left != None:
                c = Nodes[node_id].left
                children.append(c)
                while Nodes[c].right != None:
                    c = Nodes[c].right
                    children.append(c)
        print('node {0}: parent = {1}, depth = {2}, {3}, [{4}]'.format(node_id, Nodes[node_id].parent, Nodes[node_id].get_depth(), type,
                                                                       ', '.join(map(str, children))))

Submission status: Runtime Error

Solution code:
import sys

nil = -1

class Node:
    def __init__(self, p, l, r):
        self.p = p
        self.l = l
        self.r = r

def depth_rec(u, p, depth):
    depth[u] = p
    if tree[u].r != nil:
        depth_rec(tree[u].r, p, depth)
    if tree[u].l != nil:
        depth_rec(tree[u].l, p + 1, depth)
    pass

n = int(sys.stdin.readline())

tree = [Node(nil, nil, nil) for i in range(n)]
depth = [0] * n

for i in range(n):
    line = [int(i) for i in sys.stdin.readline().split()]
    vertex = line[0]

    for (j, c) in enumerate(line[2:]):
        if j == 0:
            tree[vertex].l = c
        else:
            tree[l].r = c

        l = c
        tree[c].p = vertex

'''
for i in range(n):
    print(tree[i].p, tree[i].l, tree[i].r)
'''
for i in range(n):
    if tree[i].p == nil:
        root = i

depth_rec(root, 0, depth)

# print(depth)

for vtx in range(n):
    print("node {}: parent = {}, depth = {}, ".format(vtx, tree[vtx].p, depth[vtx]), end = "")

    if tree[vtx].p == nil:
        print("root, ", end = "")
    elif tree[vtx].l == nil:
        print("leaf, ", end = "")
    else:
        print("internal node, ", end = "")

    children = []
    child = tree[vtx].l

    while child != nil:
        children.append(child)
        child = tree[child].r

    print(children)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10 ** 6)

nil = -1

class Node:
    def __init__(self, p, l, r):
        self.p = p
        self.l = l
        self.r = r

def depth_rec(u, p, depth):
    depth[u] = p
    if tree[u].r != nil:
        depth_rec(tree[u].r, p, depth)
    if tree[u].l != nil:
        depth_rec(tree[u].l, p + 1, depth)
    pass

n = int(sys.stdin.readline())

tree = [Node(nil, nil, nil) for i in range(n)]
depth = [0] * n

for i in range(n):
    line = [int(i) for i in sys.stdin.readline().split()]
    vertex = line[0]

    for (j, c) in enumerate(line[2:]):
        if j == 0:
            tree[vertex].l = c
        else:
            tree[l].r = c

        l = c
        tree[c].p = vertex

'''
for i in range(n):
    print(tree[i].p, tree[i].l, tree[i].r)
'''
for i in range(n):
    if tree[i].p == nil:
        root = i

depth_rec(root, 0, depth)

# print(depth)

for vtx in range(n):
    print("node {}: parent = {}, depth = {}, ".format(vtx, tree[vtx].p, depth[vtx]), end = "")

    if tree[vtx].p == nil:
        print("root, ", end = "")
    elif tree[vtx].l == nil:
        print("leaf, ", end = "")
    else:
        print("internal node, ", end = "")

    children = []
    child = tree[vtx].l

    while child != nil:
        children.append(child)
        child = tree[child].r

    print(children)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10 ** 8)

nil = -1

class Node:
    def __init__(self, p, l, r):
        self.p = p
        self.l = l
        self.r = r

def depth_rec(u, p, depth):
    depth[u] = p
    if tree[u].r != nil:
        depth_rec(tree[u].r, p, depth)
    if tree[u].l != nil:
        depth_rec(tree[u].l, p + 1, depth)
    pass

n = int(sys.stdin.readline())

tree = [Node(nil, nil, nil) for i in range(n)]
depth = [0] * n

for i in range(n):
    line = [int(i) for i in sys.stdin.readline().split()]
    vertex = line[0]

    for (j, c) in enumerate(line[2:]):
        if j == 0:
            tree[vertex].l = c
        else:
            tree[l].r = c

        l = c
        tree[c].p = vertex

'''
for i in range(n):
    print(tree[i].p, tree[i].l, tree[i].r)
'''
for i in range(n):
    if tree[i].p == nil:
        root = i

depth_rec(root, 0, depth)

# print(depth)

for vtx in range(n):
    print("node {}: parent = {}, depth = {}, ".format(vtx, tree[vtx].p, depth[vtx]), end = "")

    if tree[vtx].p == nil:
        print("root, ", end = "")
    elif tree[vtx].l == nil:
        print("leaf, ", end = "")
    else:
        print("internal node, ", end = "")

    children = []
    child = tree[vtx].l

    while child != nil:
        children.append(child)
        child = tree[child].r

    print(children)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10 ** 9)

nil = -1

class Node:
    def __init__(self, p, l, r):
        self.p = p
        self.l = l
        self.r = r

def depth_rec(u, p, depth):
    depth[u] = p
    if tree[u].r != nil:
        depth_rec(tree[u].r, p, depth)
    if tree[u].l != nil:
        depth_rec(tree[u].l, p + 1, depth)
    pass

n = int(sys.stdin.readline())

tree = [Node(nil, nil, nil) for i in range(n)]
depth = [0] * n

for i in range(n):
    line = [int(i) for i in sys.stdin.readline().split()]
    vertex = line[0]

    for (j, c) in enumerate(line[2:]):
        if j == 0:
            tree[vertex].l = c
        else:
            tree[l].r = c

        l = c
        tree[c].p = vertex

'''
for i in range(n):
    print(tree[i].p, tree[i].l, tree[i].r)
'''
for i in range(n):
    if tree[i].p == nil:
        root = i

depth_rec(root, 0, depth)

# print(depth)

for vtx in range(n):
    print("node {}: parent = {}, depth = {}, ".format(vtx, tree[vtx].p, depth[vtx]), end = "")

    if tree[vtx].p == nil:
        print("root, ", end = "")
    elif tree[vtx].l == nil:
        print("leaf, ", end = "")
    else:
        print("internal node, ", end = "")

    children = []
    child = tree[vtx].l

    while child != nil:
        children.append(child)
        child = tree[child].r

    print(children)

Submission status: Runtime Error

Solution code:
fin = open('sample.txt')
input = fin.readline


def main():
    N = int(input())
    A = [0] * N
    node_info = [[-1, 0, 'internal node', None] for _ in range(int(1E5 + 1))]
    for i in range(N):
        A[i] = [int(i) for i in input().strip().split()]
    for line in A:
        if line[1] != 0:
            node_info[line[0]][3] = line[2:]
            for c in line[2:]:
                node_info[c][0] = line[0]

    for line in A:
        pid = node_info[line[0]][0]
        if pid == -1:
            node_info[line[0]][2] = 'root'
        else:
            if node_info[line[0]][3] is None:
                node_info[line[0]][2] = 'leaf'
        if node_info[line[0]][3] is None:
            node_info[line[0]][3] = ['']

        depth = 0
        while pid != -1:
            depth += 1
            pid = node_info[pid][0]
        node_info[line[0]][1] = depth

    for line in sorted(A, key=lambda a: a[0]):
        print('node {}: parent = {}, depth = {}, {}, [{}]'.format(
            line[0], node_info[line[0]][0],
            node_info[line[0]][1], node_info[line[0]][2], ', '.join([str(i) for i in node_info[line[0]][3]]))
        )


if __name__ == '__main__':
    main()

Submission status: Runtime Error

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


def setdepth(u, p):
    depths[u] = p
    if trees[u].right != -1:
        # ???????????????????????±???????¨????
        setdepth(trees[u].right, p)
    if trees[u].left != -1:
        # ??????????????????????????±???+1????¨????
        setdepth(trees[u].left, p+1)


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]
    jisu = l[1]
    # 2???????????????????????§???????´??????????
    childs = l[2:]
    for j in range(jisu):
        child = childs[j]
        if j == 0:
            trees[no].left = child

        if j != len(childs)-1:
            trees[child].right = childs[j+1]

        trees[child].parent = no

r = 0
for i in range(N):
    if trees[i].parent == -1:
        r = i

depths = [-1] * N
setdepth(r, 0)

for i in range(N):
    type = ""
    if trees[i].parent == -1: type = "root"
    elif trees[i].left == -1: type = "leaf"
    else: type = "internal node"
    childs = "["
    child = trees[i].left
    while child != -1:
        childs += str(child)
        child = trees[child].right
        if child != -1: childs += ", "
    childs += "]"

    print("node {0}: parent = {1}, depth = {2}, {3}, {4}".format(i, trees[i].parent, depths[i], type, childs))

Submission status: Runtime Error

Solution code:
import sys

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


def setdepth(u, p):
    depths[u] = p
    if trees[u].right != -1:
        # ???????????????????????±???????¨????
        setdepth(trees[u].right, p)
    if trees[u].left != -1:
        # ??????????????????????????±???+1????¨????
        setdepth(trees[u].left, p+1)

sys.setrecursionlimit(200000)
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]
    jisu = l[1]
    # 2???????????????????????§???????´??????????
    childs = l[2:]
    for j in range(jisu):
        child = childs[j]
        if j == 0:
            trees[no].left = child

        if j != len(childs)-1:
            trees[child].right = childs[j+1]

        trees[child].parent = no

r = 0
for i in range(N):
    if trees[i].parent == -1:
        r = i

depths = [-1] * N
setdepth(r, 0)

for i in range(N):
    type = ""
    if trees[i].parent == -1: type = "root"
    elif trees[i].left == -1: type = "leaf"
    else: type = "internal node"
    childs = "["
    child = trees[i].left
    while child != -1:
        childs += str(child)
        child = trees[child].right
        if child != -1: childs += ", "
    childs += "]"

    print("node {0}: parent = {1}, depth = {2}, {3}, {4}".format(i, trees[i].parent, depths[i], type, childs))

Submission status: Runtime Error

Solution code:
class Node:
    parent = NIL
    left = NIL
    right = NIL
    label = ""


def show_info(u):
    global T, D
    if T[i].parent == NIL:
        T[u].label = "root"
    elif T[i].left == NIL:
        T[u].label = "leaf"
    else:
        T[u].label = "internal node"
    print('node {0}: parent = {1}, depth = {2}, {3}, {4}'.format(u, T[u].parent, D[u], T[u].label, getChildren(u)))


def getChildren(u):
    global T
    c = T[u].left
    R =[]
    while c != NIL:
        R.append(c)
        c = T[c].right
    return R


def setDepth(u,p):
    global T, D
    D[u] = p
    if T[u].right != NIL:
        setDepth(T[u].right, p)
    if T[u].left != NIL:
        setDepth(T[u].left, p + 1)


if __name__ == "__main__":
    n = int(input())
    T = [None] * n
    D = [None] * n
    for i in range(n):
        T[i] = Node()
    for i in range(n):
        tmp = list(map(int, input().split()))
        id = tmp.pop(0)
        k = tmp.pop(0)
        C = tmp
        if k != 0:
            T[id].left = C[0]
            for j in range(len(C)):
                T[C[j]].parent = id
            for j in range(len(C) - 1):
                T[C[j]].right = C[j + 1]
    # ??±????¨????
    setDepth(0, 0)
    for i in range(n):
        show_info(i)

Submission status: Runtime Error

Solution code:
NIL = -1


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


def show_info(u):
    global T, D
    print('node {0}: parent = {1}, depth = {2}, {3}, {4}'.format(u, T[u].parent, D[u], T[u].label, getChildren(u)))


def setLabel(n):
    for i in range(n):
        if T[i].parent == NIL:
            T[i].label = "root"
        elif T[i].left == NIL:
            T[i].label = "leaf"
        else:
            T[i].label = "internal node"


def getChildren(u):
    global T
    c = T[u].left
    R =[]
    while c != NIL:
        R.append(c)
        c = T[c].right
    return R


def setDepth(u,p):
    global T, D
    D[u] = p
    if T[u].right != NIL:
        setDepth(T[u].right, p)
    if T[u].left != NIL:
        setDepth(T[u].left, p + 1)


if __name__ == "__main__":
    n = int(input())
    T = [None] * n
    D = [0] * n
    for i in range(n):
        T[i] = Node()
    for i in range(n):
        tmp = list(map(int, input().split()))
        id = tmp.pop(0)
        k = tmp.pop(0)
        C = tmp
        if k != 0:
            T[id].left = C[0]
            for j in range(len(C)):
                T[C[j]].parent = id
            for j in range(len(C) - 1):
                T[C[j]].right = C[j + 1]
    setLabel(n)
    for i in range(n):
        if T[i].label == "root":
            root = i
    # ??±????¨????
    setDepth(root, 0)
    for i in range(n):
        show_info(i)

Submission status: Runtime Error

Solution code:
NIL = -1


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


def setDepth(u,d):
    D[u] = d
    if T[u].left != NIL:
        setDepth(T[u].left,d + 1)
    if T[u].right != NIL:
        setDepth(T[u].right, d)


def getChildren(u):
    c = T[u].left
    result = []
    while c != NIL:
        result.append(c)
        c = T[c].right
    return result


n = int(input())
T = [0] * n
D = [0] * n
root_num = NIL

# ?????????????????¨??????
for i in range(n):
    T[i] = Node()
for i in range(n):
    tmp = list(map(int, input().split()))
    id = tmp.pop(0)
    k = tmp.pop(0)
    C = tmp
    if k != 0:
        for c in C:
            T[c].parent = id
        T[id].left = C[0]
        for j in range(len(C) - 1):
            T[C[j]].right = C[j + 1]


# ??????????????°&??±????¨????
for i in range(n):
    if T[i].parent == NIL:
        root_num = i
        T[i].label = "root"
    elif T[i].left == NIL:
        T[i].label = "leaf"
    else:
        T[i].label = "internal node"
setDepth(root_num, 0)

for i in range(n):
    print("node {0}: parent = {1}, depth = {2}, {3}, {4}".format(i, T[i].parent, D[i], T[i].label, getChildren(i)))

Submission status: Runtime Error

Solution code:
class Node:
    def __init__(self, num, parent, children):
        self.id = num
        self.parent = -1
        self.depth = 0
        self.type = None
        self.children = children
         
    def show(self):
        print('node {0}: parent = {1}, depth = {2}, {3}, {4}'.format(self.id,self.parent,self.depth,self.type,self.children))
 
 
def set_node(node_data):
    L = list(map(int, node_data.split()))
    num = i_l[0]
    children = i_l[2:]
    node = Node(num, -1, children)
    T[num] = node
    for n in children:
        T[-1] -= n
 
def set_pdt(n_i, parent, depth):
    node = T[n_i]
    node.parent = parent
    node.depth = depth
    if node.children:
        node.type = 'internal node'
        for n in node.children:
            set_pdt(n, n_i, depth + 1)
    else:
        node.type = 'leaf'
 
n = int(input())
 
T = [None] * n
 
T.append(int(n * (n - 1) / 2))
 
for i in range(n):
    x = input()
    set_node(x)
 
set_pdt(T[-1], -1, 0)
 
T[T[-1]].type ='root'
 
for n in T[:-1]:
    n.show()

Submission status: Runtime Error

Solution code:
import sys


def dep(u, p):
    D[u] = p
    if tree[u][2] != NIL:
        dep(tree[u][2], p)
    if tree[u][1] != NIL:
        dep(tree[u][1], p+1)


def print_ans():
    for i in range(n):
        if tree[i][0] == NIL:
            typea = "root"
        elif tree[i][1] == NIL:
            typea = "leaf"
        else:
            typea = "internal node"
        child = []
        b = tree[i]
        if b[1] != NIL:
            child.append(b[1])
            b = tree[b[1]]
            while b[2] != NIL:
                child.append(b[2])
                b = tree[b[2]]
        print("node {}: parent = {}, depth = {}, {}, {}"
              .format(i, tree[i][0], D[i], typea, child))


if __name__ == "__main__":
    NIL = -1
    n = int(sys.stdin.readline())
    tree = [[NIL, NIL, NIL] for i in range(n)]
    D = [0 for i in range(n)]
    for a in sys.stdin.readlines():
        a = list(map(int, a.split()))
        if a[1] > 0:
            tree[a[0]][1] = a[2]    # ???????????????
            for i in range(a[1]):
                tree[a[i+2]][0] = a[0] # ????????????
                if i != a[1] - 1:
                    tree[a[i+2]][2] = a[i+3] # ??????????????????
    for i in range(n):
        if tree[i][0] == NIL:
            r = i
            break
    dep(r, 0)
    print_ans()

Submission status: Runtime Error

Solution code:
import sys


def dep(u, p):
    D[u] = p
    if tree[u][2] != NIL:
        dep(tree[u][2], p)
    if tree[u][1] != NIL:
        dep(tree[u][1], p+1)


def print_ans():
    for i in range(n):
        if tree[i][0] == NIL:
            typea = "root"
        elif tree[i][1] == NIL:
            typea = "leaf"
        else:
            typea = "internal node"
        print("node {}: parent = {}, depth = {}, {}, {}"
              .format(i, tree[i][0], D[i], typea, tree[i][3]))


if __name__ == "__main__":
    NIL = -1
    n = int(sys.stdin.readline())
    tree = [[NIL, NIL, NIL] for i in range(n)]
    D = [0 for i in range(n)]
    for a in sys.stdin.readlines():
        a = list(map(int, a.split()))
        tree[a[0]].append(a[2:])
        if a[1] > 0:
            tree[a[0]][1] = a[2]    # ???????????????
            for i in range(a[1]):
                tree[a[i+2]][0] = a[0] # ????????????
                if i != a[1] - 1:
                    tree[a[i+2]][2] = a[i+3] # ??????????????????
    for i in range(n):
        if tree[i][0] == NIL:
            r = i
            break
    dep(r, 0)
    print_ans()

Submission status: Runtime Error

Solution code:
import sys


def dep(u, p):
    D[u] = p
    if tree[u][2] != NIL:
        dep(tree[u][2], p)
    if tree[u][1] != NIL:
        dep(tree[u][1], p+1)


def print_ans():
    for i in range(n):
        print("node {}: parent = {}, depth = {}, {}, {}"
              .format(i, tree[i][0], D[i], tree[i][4], tree[i][3]))


if __name__ == "__main__":
    NIL = -1
    n = int(sys.stdin.readline())
    tree = [[NIL, NIL, NIL] for i in range(n)]
    D = [0 for i in range(n)]
    for a in sys.stdin.readlines():
        a = list(map(int, a.split()))
        tree[a[0]].append(a[2:])
        if a[1] > 0:
            tree[a[0]][1] = a[2]    # ???????????????
            for i in range(a[1]):
                tree[a[i+2]][0] = a[0] # ????????????
                if i != a[1] - 1:
                    tree[a[i+2]][2] = a[i+3] # ??????????????????
    for i in range(n):
        if tree[i][0] == NIL:
            tree[i].append("root")
            r = i
        elif tree[i][1] == NIL:
            tree[i].append("leaf")
        else:
            tree[i].append("internal node")
    dep(r, 0)
    print_ans()

Submission status: Runtime Error

Solution code:
import sys


def dep(u, p):
    D[u] = p
    if tree[u][2] != NIL:
        dep(tree[u][2], p)
    if tree[u][1] != NIL:
        dep(tree[u][1], p+1)


def print_ans():
    for i in range(n):
        print("node {}: parent = {}, depth = {}, {}, {}"
              .format(i, tree[i][0], D[i],
                      "root" if tree[i][0] == NIL else "leaf" if tree[i][1] == NIL else "internal node",
                      tree[i][3]))


if __name__ == "__main__":
    NIL = -1
    n = int(sys.stdin.readline())
    tree = [[NIL, NIL, NIL] for i in range(n)]
    D = [0 for i in range(n)]
    root = set(range(n))
    for a in sys.stdin.readlines():
        a = list(map(int, a.split()))
        tree[a[0]].append(a[2:])
        if a[1] > 0:
            tree[a[0]][1] = a[2]    # ???????????????
            for i in range(a[1]):
                tree[a[i+2]][0] = a[0] # ????????????
                if i != a[1] - 1:
                    tree[a[i+2]][2] = a[i+3] # ??????????????????
        root -= set(a[2:])
    dep(root.pop(), 0)
    print_ans()

Submission status: Runtime Error

Solution code:
import sys

NIL = -1

def set_depth(v, depth):
    tree[v][2] = depth
    
    if child in tree[v][1]:
        set_depth(child, depth + 1)

N = int(input())
tree = [[NIL, [], 0, 'leaf'] for _ in range(N)]

for _ in range(N):
    line = [int(i) for i in sys.stdin.readline().split()]
    t_id = line[0]
    children = line[2:]
    tree[t_id][1] = children
    
    if children:
        tree[t_id][3] = 'internal node'
    
    for child in children:
        tree[child][0] = t_id
        
for t_id in range(N):
    if tree[t_id][0] == NIL:
        tree[t_id][3] = 'root'
        r = t_id
        break

set_depth(r, 0)

for t_id in range(N):
    parent = tree[t_id][0]
    depth = tree[t_id][2]
    children = tree[t_id][1]
    type_t = tree[t_id][3]
    
    print('node {}: parent = {}, depth = {}, {}, {}'.format(t_id, parent, depth, type_t, children))

Submission status: Runtime Error

Solution code:
n = int(input())
tree = {}

for i in range(n):
    row = [int(k) for k in input().split()]
    id = row[0]
    ch = row[2:]
    val = tree.get(id, [])
    val += ch
    tree[id] = val



def printInfo(id):
    parent = -1
    depth = 0
    for p in tree.keys():
        if id in tree[p]:
            parent = p
            break
    while True:
        for p in tree.keys():
            if id in tree[p]:
                depth += 1
                id = p
                break

        if p == tree.keys()[-1]:
            break
    for p in tree.keys():
        if id in tree[p]:
            depth += 1
    if parent == -1:
        type = 'root'
    elif tree[id] != []:
        type = 'internal node'
    else:
        type = "leaf"
    print('node %d: parent = %d, depth = %d, %s, %s' %(id,parent,depth,type,str(tree[id])))
print(tree)
for p in tree.keys():
    printInfo(p)

Submission status: Runtime Error

Solution code:
n = int(input())
tree = {}

for i in range(n):
    row = [int(k) for k in input().split()]
    id = row[0]
    ch = row[2:]
    val = tree.get(id, [])
    val += ch
    tree[id] = val



def printInfo(id):
    parent = -1
    depth = 0
    for p in tree.keys():
        if id in tree[p]:
            parent = p
            break
    while True:
        for p in tree.keys():
            if id in tree[p]:
                depth += 1
                id = p
                break

        if p == tree.keys()[-1]:
            break
    for p in tree.keys():
        if id in tree[p]:
            depth += 1
    if parent == -1:
        type = 'root'
    elif tree[id] != []:
        type = 'internal node'
    else:
        type = "leaf"
    print('node %d: parent = %d, depth = %d, %s, %s' %(id,parent,depth,type,str(tree[id])))

for p in tree.keys():
    printInfo(p)

Submission status: Runtime Error

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

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

for i in range(n):
    id, left, right = map(int, input().split())
    nodes[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)