Problem:

Binary Tree

A rooted binary tree is a tree with a root node in which every node has at most two children.

Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T:

node ID of u

parent of u

sibling of u

the number of children of u

depth of u

height of u

node type (root, internal node or leaf)

If two nodes have the same parent, they are siblings. Here, if u and v have the same parent, we say u is a sibling of v (vice versa).

The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf.

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 lines, 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

Print the information of each node in the following format:

node id: parent = p, sibling = s, degree = deg, depth = dep, height = h, type

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

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

deg, dep and h are the number of children, depth and height of the node respectively.

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.

Please follow the format presented in a sample output below.

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

node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root
node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node
node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf
node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf
node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node
node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node
node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf
node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf
node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf

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:
node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root
node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node
node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf
node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf
node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node
node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node
node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf
node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf
node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf

Submission status: Accepted

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


def bin_tree(lst, n):
    """
        tree[0]: node
        tree[1]: parent
        tree[2]: sibling
        tree[3]: degree
        tree[4]: depth
        tree[5]: height
    """
    info = [[-1, -1, -1, -1, -1, -1] for n in range(0, n)]
    degree = 0
    for node, left, right in lst:
        if left >= 0:
            info[left][1] = node
            info[left][2] = right
            degree += 1

        if right >= 0:
            info[right][1] = node
            info[right][2] = left
            degree += 1

        info[node][0] = node
        info[node][3] = degree

        degree = 0

    root = -1
    for node in info:
        root = node[0]
        if node[1] == -1:
            break

    get_depth(lst, root, info)
    get_height(lst, root, info)
    print_info(info)


def get_height(tree, root, info):
    def _get_height(node, depth):
        if node == -1:
            return 0

        left_height = _get_height(tree[node][1], depth + 1)
        right_height = _get_height(tree[node][2], depth + 1)

        if left_height > right_height:
            info[node][5] = left_height
        else:
            info[node][5] = right_height

        return info[node][5] + 1

    _get_height(root, 0)


def get_depth(tree, root, info):
    def _get_depth(node, depth):
        if node == -1:
            return

        info[node][4] = depth
        _get_depth(tree[node][1], depth + 1)
        _get_depth(tree[node][2], depth + 1)

    _get_depth(root, 0)


def print_info(info):
    for node, parent, sibling, degree, depth, height in info:
        if parent == -1:
            _type = "root"
        elif degree != 0:
            _type = "internal node"
        else:
            _type = "leaf"

        print("node {0}: parent = {1}, sibling = {2}, degree = {3}, depth = {4}, height = {5}, {6}".format(node, parent, sibling, degree, depth, height, _type))


if __name__ == "__main__":
    n = int(input())
    lst = [[int(n) for n in val.split()] for val in sys.stdin.readlines()]
    lst.sort(key=lambda x: x[0])
    bin_tree(lst, n)

Submission status: Accepted

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

class Node():
    def __init__(self, parent=-1, left=-1, right=-1, depth=0, height=0, sibling=-1, degree=0):
        self.parent = parent
        self.left = left
        self.right = right
        self.depth = depth
        self.height = height
        self.sibling = sibling
        self.degree = degree

if __name__ == '__main__':

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

    for _ in range(n):
        i, left, right = [int(s) for s in input().split(" ")]
        has_left = (left != -1)
        has_right = (right != -1)
        if has_left:
            T[i].left = left
            T[left].parent = i
            T[i].degree += 1
        if has_right:
            T[i].right = right
            T[right].parent = i
            T[i].degree += 1
        if has_left and has_right:
            T[left].sibling = right
            T[right].sibling = left

    def setDepth(u, p):
        T[u].depth = p
        if T[u].right != -1:
            setDepth(T[u].right, p + 1)
        if T[u].left != -1:
            setDepth(T[u].left, p + 1)

    def setHeight(u):
        h1 = 0
        h2 = 0
        if T[u].right != -1:
            h1 = setHeight(T[u].right) + 1
        if T[u].left != -1:
            h2 = setHeight(T[u].left) + 1
        T[u].height = max(h1, h2)
        return T[u].height

    for i, n in enumerate(T):
        if n.parent == -1:
            root = i
        
    setDepth(root, 0)
    setHeight(root)

    for i, node in enumerate(T):
        if node.parent == -1:
            n_type = "root"
        elif node.left != -1 or node.right != -1:
            n_type = "internal node"
        else:
            n_type = "leaf"

        print("node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}".format(
            i, node.parent, node.sibling, node.degree, node.depth, node.height, n_type))

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
class Tree:
    __slots__ = ['id', 'p', 'sibling', 'degree', 'depth', 'height', 'type', 'c']
    def __init__(self, id):
        self.id = id
        self.p = -1
        self.sibling = -1
        self.degree = 0
        self.depth = -1
        self.height = 0
        self.type = "leaf"
        self.c = []
    def __str__(self):
        return f"node {self.id}: parent = {self.p}, sibling = {self.sibling}, degree = {self.degree}, depth = {self.depth}, height = {self.height}, {self.type}"
def solve():
    n = int(input())
    if n == 1:
        input()
        print("node 0: parent = -1, sibling = -1, degree = 0, depth = 0, height = 0, root")
        return
    tree = tuple(Tree(i) for i in range(n))
    leaf_li = set()
    for _ in range(n):
        id, *c = map(int, readline().replace("-1", "").split())
        if c != []:
            tree[id].type = "internal node"
            tree[id].c = c
            for j in c:
                tree[j].p = id
            len_c = len(c)
            tree[id].degree = len_c
            if len_c == 2:
                tree[c[0]].sibling = c[1]
                tree[c[1]].sibling = c[0]
        else:
            leaf_li.add(id)
    for i in leaf_li:
        a = i
        cnt = 1
        while tree[a].p != -1 and tree[tree[a].p].height < cnt:
            tree[tree[a].p].height = cnt
            cnt += 1
            a = tree[a].p
    root = 0
    while tree[root].p != -1:
        root = tree[root].p
    tree[root].type = "root"
    tree[root].depth = 0
    tree[root].height = max(tree[i].height for i in tree[root].c) + 1
    def depth_check(id, d):
        d += 1
        for i in tree[id].c:
            tree[i].depth = d
            if tree[i].type != "leaf":
                depth_check(i, d)
    depth_check(root, 0)
    print("\n".join(map(str, tree)))
solve()

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
class Tree:
    __slots__ = ['id', 'p', 'sibling', 'degree', 'depth', 'height', 'type', 'c']
    def __init__(self, id):
        self.id = id
        self.p = -1
        self.sibling = -1
        self.degree = 0
        self.depth = 0
        self.height = 0
        self.type = "leaf"
        self.c = []
    def __str__(self):
        return f"node {self.id}: parent = {self.p}, sibling = {self.sibling}, degree = {self.degree}, depth = {self.depth}, height = {self.height}, {self.type}"
def solve():
    n = int(input())
    tree = tuple(Tree(i) for i in range(n))
    for _ in range(n):
        id, *c = map(int, readline().replace("-1", "").split())
        if c != []:
            tree[id].type = "internal node"
            tree[id].c = c
            for j in c:
                tree[j].p = id
            len_c = len(c)
            tree[id].degree = len_c
            if len_c == 2:
                tree[c[0]].sibling = c[1]
                tree[c[1]].sibling = c[0]
    root = 0
    while tree[root].p != -1:
        root = tree[root].p
    tree[root].type = "root"
    def depth_height_check(id, d):
        d += 1
        height = 0
        for i in tree[id].c:
            tree[i].depth = d
            if tree[i].type != "leaf":
                tree[i].height = depth_height_check(i, d) + 1
                height = max(height, tree[i].height)
        return height
    tree[root].height = depth_height_check(root, 0) + 1 if n > 1 else 0
    print("\n".join(map(str, tree)))
solve()

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
class Tree:
    __slots__ = ['id', 'p', 'sibling', 'degree', 'depth', 'height', 'type', 'c']
    def __init__(self, id):
        self.id = id
        self.p = -1
        self.sibling = -1
        self.degree = 0
        self.depth = 0
        self.height = 0
        self.type = "leaf"
        self.c = []
    def __str__(self):
        return f"node {self.id}: parent = {self.p}, sibling = {self.sibling}, degree = {self.degree}, depth = {self.depth}, height = {self.height}, {self.type}"
n = int(input())
tree = tuple(Tree(i) for i in range(n))
for _ in range(n):
    id, *c = map(int, readline().replace("-1", "").split())
    if c != []:
        tree[id].type = "internal node"
        tree[id].c = c
        for j in c:
            tree[j].p = id
        len_c = len(c)
        tree[id].degree = len_c
        if len_c == 2:
            tree[c[0]].sibling = c[1]
            tree[c[1]].sibling = c[0]
root = 0
while tree[root].p != -1:
    root = tree[root].p
tree[root].type = "root"
def depth_height_check(id, d):
    d += 1
    height = 0
    for i in tree[id].c:
        tree[i].depth = d
        if tree[i].type != "leaf":
            tree[i].height = depth_height_check(i, d) + 1
            height = max(height, tree[i].height)
    return height
tree[root].height = depth_height_check(root, 0) + 1 if n > 1 else 0
print("\n".join(map(str, tree)))

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
class Tree:
    __slots__ = ['id', 'p', 'sibling', 'degree', 'depth', 'height', 'type', 'c']
    def __init__(self, id):
        self.id = id
        self.p = -1
        self.sibling = -1
        self.degree = 0
        self.depth = 0
        self.height = 0
        self.type = "leaf"
        self.c = []
    def __str__(self):
        return f"node {self.id}: parent = {self.p}, sibling = {self.sibling}, degree = {self.degree}, depth = {self.depth}, height = {self.height}, {self.type}"
n = int(input())
tree = tuple(Tree(i) for i in range(n))
for _ in range(n):
    id, *c = map(int, readline().replace("-1", "").split())
    if c != []:
        tree[id].type = "internal node"
        tree[id].c = c
        for j in c:
            tree[j].p = id
        len_c = len(c)
        tree[id].degree = len_c
        if len_c == 2:
            tree[c[0]].sibling = c[1]
            tree[c[1]].sibling = c[0]
root = 0
while tree[root].p != -1:
    root = tree[root].p
tree[root].type = "root"
def depth_height_check(id, d):
    d += 1
    height = 0
    for i in tree[id].c:
        tree[i].depth = d
        if tree[i].type != "leaf":
            tree[i].height = depth_height_check(i, d)
            height = max(height, tree[i].height)
    return height + 1
tree[root].height = depth_height_check(root, 0) if n > 1 else 0
print("\n".join(map(str, tree)))

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
class Tree:
    __slots__ = ['id', 'p', 'sibling', 'degree', 'depth', 'height', 'type', 'c']
    def __init__(self, id):
        self.id = id
        self.p = -1
        self.sibling = -1
        self.degree = 0
        self.depth = 0
        self.height = 0
        self.type = "leaf"
        self.c = []
    def __str__(self):
        return f"node {self.id}: parent = {self.p}, sibling = {self.sibling}, degree = {self.degree}, depth = {self.depth}, height = {self.height}, {self.type}"
n = int(input())
tree = tuple(Tree(i) for i in range(n))
for _ in range(n):
    id, *c = (i for i in map(int, readline().split()) if i != -1)
    if c != []:
        tree[id].type = "internal node"
        tree[id].c = c
        for j in c:
            tree[j].p = id
        len_c = len(c)
        tree[id].degree = len_c
        if len_c == 2:
            tree[c[0]].sibling = c[1]
            tree[c[1]].sibling = c[0]
root = 0
while tree[root].p != -1:
    root = tree[root].p
tree[root].type = "root"
def depth_height_check(id, d):
    d += 1
    height = 0
    for i in tree[id].c:
        tree[i].depth = d
        if tree[i].type != "leaf":
            tree[i].height = depth_height_check(i, d)
            height = max(height, tree[i].height)
    return height + 1
tree[root].height = depth_height_check(root, 0) if n > 1 else 0
print("\n".join(map(str, tree)))

Submission status: Accepted

Solution code:
import collections

def search_topdown(node, elems, tree, depth):
    elems[node]['depth'] = depth
    if elems[node]['parent'] == -1:
        state = 'root'
    elif tree[node][0] == tree[node][1] == -1:
        state = 'leaf'
    else:
        state = 'internal node'
    elems[node]['state'] = state
    elems[node]['degree'] = len([x for x in tree[node] if x != -1])
    depth += 1
    for c in tree[node]:
        if c == -1:
            continue
        search_topdown(c, elems, tree, depth)

def search_bottomup(node, elems, tree, height):
    if 'height' in elems[node]:
        elems[node]['height'] = max(height, elems[node]['height'])
    else:
        elems[node]['height'] = height
    p = elems[node]['parent']
    if p != -1:
        sibling, another = tree[p]
        if sibling == node:
            sibling = another
    else:
        sibling = -1
    elems[node]['sibling'] = sibling
    height += 1
    if p != -1:
        search_bottomup(p, elems, tree, height)
        
if __name__ == '__main__':
    n = int(input())
    tree = collections.defaultdict(list)
    elems = collections.defaultdict(dict)
    #elems key:id, value: parent, sibling, degree, depth, height, state
    parents = list()
    leaves = set()
    node_list = list()
    for _ in range(n):
        hoge = [int(x) for x in input().split()]
        node_list.append(hoge[0])
        tree[hoge[0]].append(hoge[1])
        tree[hoge[0]].append(hoge[2])
    
    for key, value in tree.items():
        for v in value:
            if v != -1:
                elems[v]['parent'] = key
            else:
                leaves.add(key)
    
    for node in node_list:
        if not elems[node]:
            parents.append(node)
            elems[node]['parent'] = -1
    
    for p in parents:
        search_topdown(p, elems, tree, 0)
    
    for l in leaves:
        search_bottomup(l, elems, tree, 0)
    
    for key, value in sorted(elems.items()):
        print('node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'.format(key, value['parent'], value['sibling'], value['degree'], value['depth'], value['height'], value['state']))

Submission status: Accepted

Solution code:
import sys
def q(a,k):
 d[a]=k
 for b in t[a]:
  if'-1'!=b:q(b,k+1)
def n(a,k):
 if a in h:h[a]=max(h[a],k)
 else:h[a]=k
 if'-1'!=p[a]:n(p[a],k+1)
input()
t,p,s,d,h={},{},{},{},{}
for e in sys.stdin:
 x,y,z=e.split()
 t[x]=set([y,z])-set(['-1'])
 p[y]=p[z]=x
 s[y],s[z]=z,y
r=(set(t)-set(p)).pop()
p[r],s[r]=['-1']*2
q(r,0)
for i in t:
 if not t[i]:n(i,0)
print('\n'.join(f"node {i}: parent = {p[i]}, sibling = {s[i]}, degree = {len(t[i])}, depth = {d[i]}, height = {h[i]}, {'root'if d[i]==0else'internal node'if t[i]else'leaf'}"for i in map(str,sorted(map(int,t)))))

Submission status: Accepted

Solution code:
import sys
def q(a,k):
 d[a]=k
 for b in t[a]:
  if'-1'!=b:q(b,k+1)
def n(a,k):
 h[a]=max(h[a],k)if a in h else k
 if'-1'!=p[a]:n(p[a],k+1)
input()
t,p,s,d,h={},{},{},{},{}
for e in sys.stdin:
 x,y,z=e.split()
 t[x]=set([y,z])-set(['-1'])
 p[y]=p[z]=x
 s[y],s[z]=z,y
r=(set(t)-set(p)).pop()
p[r],s[r]=['-1']*2
q(r,0)
for i in t:
 if not t[i]:n(i,0)
print('\n'.join(f"node {i}: parent = {p[i]}, sibling = {s[i]}, degree = {len(t[i])}, depth = {d[i]}, height = {h[i]}, {'root'if d[i]==0else'internal node'if t[i]else'leaf'}"for i in map(str,sorted(map(int,t)))))

Submission status: Accepted

Solution code:
def q(a,k):
 d[a]=k
 for b in t[a]:
  if'-1'!=b:q(b,k+1)
def n(a,k):
 h[a]=max(h[a],k)if a in h else k
 if'-1'!=p[a]:n(p[a],k+1)
t,p,s,d,h={},{},{},{},{}
for _ in[0]*int(input()):
 x,y,z=input().split()
 t[x]=set([y,z])-set(['-1'])
 p[y]=p[z]=x
 s[y],s[z]=z,y
r=(set(t)-set(p)).pop()
p[r],s[r]=['-1']*2
q(r,0)
for i in t:
 if not t[i]:n(i,0)
print('\n'.join(f"node {i}: parent = {p[i]}, sibling = {s[i]}, degree = {len(t[i])}, depth = {d[i]}, height = {h[i]}, {'root'if d[i]==0else'internal node'if t[i]else'leaf'}"for i in map(str,sorted(map(int,t)))))

Submission status: Accepted

Solution code:
def q(a,k):
 d[a]=k
 for b in t[a]:
  if'-1'!=b:q(b,k+1)
def n(a,k):
 h[a]=max(h[a],k)if a in h else k
 if'-1'!=p[a]:n(p[a],k+1)
t,p,s,d,h={},{},{},{},{}
for _ in[0]*int(input()):
 x,y,z=input().split()
 t[x]=set([y,z])-set(['-1'])
 p[y]=p[z]=x
 s[y],s[z]=z,y
r=(set(t)-set(p)).pop()
p[r],s[r]=['-1']*2
q(r,0)
for i in t:
 if not t[i]:n(i,0)
for i in map(str,sorted(map(int,t))):print(f"node {i}: parent = {p[i]}, sibling = {s[i]}, degree = {len(t[i])}, depth = {d[i]}, height = {h[i]}, {'root'if d[i]==0else'internal node'if t[i]else'leaf'}")

Submission status: Accepted

Solution code:
def q(a,k):
 d[a]=k
 for b in t[a]:
  if'-1'!=b:q(b,k+1)
def n(a,k):
 h[a]=max(h[a],k)if a in h else k
 if'-1'!=p[a]:n(p[a],k+1)
t,p,s,d,h={},{},{},{},{}
for _ in[0]*int(input()):
 x,y,z=input().split()
 t[x]=set([y,z])-set(['-1'])
 p[y]=p[z]=x
 s[y],s[z]=z,y
r=(set(t)-set(p)).pop()
p[r]=s[r]='-1'
q(r,0)
for i in t:
 if not t[i]:n(i,0)
for i in map(str,sorted(map(int,t))):
 print(f"node {i}: parent = {p[i]}, sibling = {s[i]}, degree = {len(t[i])}, depth = {d[i]}, height = {h[i]}, {'root'if d[i]==0else'internal node'if t[i]else'leaf'}")

Submission status: Accepted

Solution code:
def q(a,k):
 d[a]=k
 for b in t[a]:
  if'-1'!=b:q(b,k+1)
def n(a,k):
 h[a]=max(h[a],k)if a in h else k
 if'-1'!=p[a]:n(p[a],k+1)
t,p,s,d,h={},{},{},{},{}
for _ in[0]*int(input()):
 x,y,z=input().split()
 t[x]=set([y,z])-{'-1'}
 p[y]=p[z]=x
 s[y],s[z]=z,y
r=(set(t)-set(p)).pop()
p[r]=s[r]='-1'
q(r,0)
for i in t:
 if not t[i]:n(i,0)
for i in map(str,sorted(map(int,t))):
 print(f"node {i}: parent = {p[i]}, sibling = {s[i]}, degree = {len(t[i])}, depth = {d[i]}, height = {h[i]}, {'root'if d[i]==0else'internal node'if t[i]else'leaf'}")

Submission status: Accepted

Solution code:
def q(a,k):
 d[a]=k
 for b in t[a]:
  if'-1'!=b:q(b,k+1)
def n(a,k):
 h[a]=max(h[a],k)if a in h else k
 if'-1'!=p[a]:n(p[a],k+1)
t,p,s,d,h={},{},{},{},{}
N=int(input())
for _ in[0]*N:
 x,y,z=input().split()
 t[x]=set([y,z])-{'-1'}
 p[y]=p[z]=x
 s[y],s[z]=z,y
r=(set(t)-set(p)).pop()
p[r]=s[r]='-1'
q(r,0)
for i in t:
 if not t[i]:n(i,0)
for i in map(str,range(N)):
 print(f"node {i}: parent = {p[i]}, sibling = {s[i]}, degree = {len(t[i])}, depth = {d[i]}, height = {h[i]}, {'root'if d[i]==0else'internal node'if t[i]else'leaf'}")

Submission status: Accepted

Solution code:
N = int(input())
tree = [None] * N
root = set(range(N))
for _ in [0] * N:
    i, l, r = list(map(int, input().split()))
    tree[i] = [l,r] + [None] * 5  # parent(2), sibling(3), degree(4), depth(5), height(6)
    root -= {l, r}

def set_pd(i, parent, sibling, depth):
    if i == -1:return -1
    node = tree[i]
    l, r = node[0], node[1]
    node[2], node[3], node[5] = parent, sibling, depth
    node[4] = (l != -1) + (r != -1)
    height = node[6] = max(set_pd(l, i, r, depth + 1), set_pd(r, i, l, depth + 1)) + 1
    return height

set_pd(root.pop(), -1, -1, 0)

for i, node in enumerate(tree):
    print('node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'.format(
        i, *node[2:], 'root' if not node[5] else 'internal node' if node[4] else 'leaf'))

Submission status: Accepted

Solution code:
N=int(input())
t=[0]*N
r=set(range(N))
for _ in[0]*N:
 x,y,z=list(map(int,input().split()))
 t[x]=[y,z]+[0]*5
 r-={y,z}
def f(i,p,s,d):
 if i<0:return-1
 l,r=t[i][:2]
 t[i][2:]=[p,s,(l!=-1)+(r!=-1),d,max(f(l,i,r,d+1),f(r,i,l,d+1))+1]
 return t[i][-1]
f(r.pop(),-1,-1,0)
for i in range(N):
 print('node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'.format(i,*t[i][2:],'root'if not t[i][5]else'internal node'if t[i][4]else'leaf'))

Submission status: Accepted

Solution code:
N=int(input())
t=[0]*N
r=set(range(N))
for _ in[0]*N:
 x,y,z=list(map(int,input().split()))
 t[x]=[y,z]+[0]*2+[(y!=-1)+(z!=-1)]+[0]*2
 r-={y,z}
def f(i,p,s,d):
 if i<0:return-1
 l,r=t[i][:2]
 t[i][2:]=[p,s,t[i][4],d,max(f(l,i,r,d+1),f(r,i,l,d+1))+1]
 return t[i][-1]
f(r.pop(),-1,-1,0)
for i in range(N):
 print('node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'.format(i,*t[i][2:],'root'if not t[i][5]else'internal node'if t[i][4]else'leaf'))

Submission status: Accepted

Solution code:
N=int(input())
t=[0]*N
r=set(range(N))
for _ in[0]*N:
 x,y,z=list(map(int,input().split()))
 t[x]=[y,z,0,0,(y!=-1)+(z!=-1),0,0]
 r-={y,z}
def f(i,p,s,d):
 if i<0:return-1
 l,r=t[i][:2]
 t[i][2:]=[p,s,t[i][4],d,max(f(l,i,r,d+1),f(r,i,l,d+1))+1]
 return t[i][-1]
f(r.pop(),-1,-1,0)
for i in range(N):
 print('node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'.format(i,*t[i][2:],'root'if not t[i][5]else'internal node'if t[i][4]else'leaf'))

Submission status: Accepted

Solution code:
N=int(input())
t=[0]*N
r=set(range(N))
for _ in[0]*N:
 e=list(map(int,input().split()))
 t[e[0]]=e[1:]+[0]*5
 r-=set(e[1:])
def f(i,p,s,d):
 if i<0:return-1
 l,r=t[i][:2]
 t[i][2:]=[p,s,(l!=-1)+(r!=-1),d,max(f(l,i,r,d+1),f(r,i,l,d+1))+1]
 return t[i][-1]
f(r.pop(),-1,-1,0)
for i in range(N):
 print('node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'.format(i,*t[i][2:],'root'if not t[i][5]else'internal node'if t[i][4]else'leaf'))

Submission status: Accepted

Solution code:
N=int(input())
t=[0]*N
r=set(range(N))
for _ in t:
 x,y,z=list(map(int,input().split()))
 t[x]=[y,z]+[0]*5
 r-={y,z}
def f(i,p,s,d):
 if i<0:return-1
 l,r=t[i][:2]
 t[i][2:]=[p,s,(l!=-1)+(r!=-1),d,max(f(l,i,r,d+1),f(r,i,l,d+1))+1]
 return t[i][-1]
f(r.pop(),-1,-1,0)
for i in range(N):
 print('node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'.format(i,*t[i][2:],'root'if not t[i][5]else'internal node'if t[i][4]else'leaf'))

Submission status: Accepted

Solution code:
N=int(input())
t=[0]*N
r=set(range(N))
for _ in[0]*N:
 x,y,z=map(int,input().split())
 t[x]=[y,z]+[0]*5
 r-={y,z}
def f(i,p,s,d):
 if i<0:return-1
 l,r=t[i][:2]
 t[i][2:]=[p,s,(l!=-1)+(r!=-1),d,max(f(l,i,r,d+1),f(r,i,l,d+1))+1]
 return t[i][-1]
f(r.pop(),-1,-1,0)
for i in range(N):
 print('node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'.format(i,*t[i][2:],'root'if not t[i][5]else'internal node'if t[i][4]else'leaf'))

Submission status: Accepted

Solution code:
N=int(input())
t=[0]*N
r=set(range(N))
for _ in[0]*N:
 x,y,z=map(int,input().split())
 t[x]=[y,z]+[0]*5
 r-={y,z}
def f(i,p,s,d):
 if i<0:return-1
 k=t[i]
 l,r=k[:2]
 k[2:]=[p,s,(l!=-1)+(r!=-1),d,max(f(l,i,r,d+1),f(r,i,l,d+1))+1]
 return t[i][-1]
f(r.pop(),-1,-1,0)
for i in range(N):
 print('node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'.format(i,*t[i][2:],'root'if not t[i][5]else'internal node'if t[i][4]else'leaf'))

Submission status: Accepted

Solution code:
class Tree:
    nodes = []
    def __init__(self):
        self.root = None
    def insert(self, nodenum, leftnum, rightnum):
        if leftnum != -1:
            self.nodes[nodenum].left = self.nodes[leftnum]
            self.nodes[leftnum].type_ = "internal node"
            self.nodes[leftnum].parent = self.nodes[nodenum]
            self.nodes[nodenum].degree += 1
        else:
            self.nodes[nodenum].left = -1
        if rightnum != -1:
            self.nodes[nodenum].right = self.nodes[rightnum]
            self.nodes[rightnum].type_ = "internal node"
            self.nodes[rightnum].parent = self.nodes[nodenum]
            self.nodes[nodenum].degree += 1
        else:
            self.nodes[nodenum].right = -1
        if leftnum != -1 and rightnum != -1:
            self.nodes[leftnum].sibling = rightnum
            self.nodes[rightnum].sibling = leftnum
    def depth(self, node):
        if node.left != -1:
            node.left.depth += node.depth + 1
            self.depth(node.left)
        if node.right != -1:
            node.right.depth += node.depth + 1
            self.depth(node.right)
    def height(self, node):
        if node.left == -1 and node.right == -1:
            node.type_ = "leaf"
            return 0
        elif node.left == -1:
            x = self.height(node.right)
            node.height = x + 1
            return x + 1
        elif node.right == -1:
            x = self.height(node.left)
            node.height = x + 1
            return x + 1
        else:
            x = max(self.height(node.left), self.height(node.right)) + 1
            node.height = x
            return x
class Node:
    def __init__(self, label, left = -1, right = -1):
        self.label = label
        self.type_ = "root"
        self.parent = -1
        self.sibling = -1
        self.depth = 0
        self.height = 0
        self.degree = 0
        self.left = left
        self.right = right

tree = Tree()
n = int(input())
for i in range(n):
    tree.nodes.append(Node(i))
for i in range(n):
    num, left, right = map(int, input().split())
    tree.insert(num, left, right)
for i in tree.nodes:
    if i.parent == -1:
        tree.depth(i)
        tree.height(i)
if n == 1:
    tree.nodes[0].type_ = "root"
for i in tree.nodes:
    print("node {0:}: parent = ".format(i.label), end = "")
    if i.parent == -1:
        print(i.parent, end = "")
    else:
        print(i.parent.label, end = "")
    print(", sibling = {0:}, degree = {1:}, depth = {2:}, height = {3:}, {4:}".format(i.sibling, i.degree, i.depth, i.height, i.type_))

Submission status: Accepted

Solution code:
from enum import IntEnum


class Attrs(IntEnum):
    LEFT = 0
    RIGHT = 1
    PARENT = 2
    SIBLING = 3
    DEPTH = 4
    HEIGHT = 5


def parents(nodes):
    for i, node in enumerate(nodes):
        if node[Attrs.LEFT] != -1:
            nodes[node[Attrs.LEFT]][Attrs.PARENT] = i
            nodes[node[Attrs.LEFT]][Attrs.SIBLING] = node[Attrs.RIGHT]
        if node[Attrs.RIGHT] != -1:
            nodes[node[Attrs.RIGHT]][Attrs.PARENT] = i
            nodes[node[Attrs.RIGHT]][Attrs.SIBLING] = node[Attrs.LEFT]


def depth_and_heights(nodes):
    def depth(n):
        if nodetype(n) != "root" and n[Attrs.DEPTH] == 0:
            n[Attrs.DEPTH] = depth(nodes[n[Attrs.PARENT]]) + 1
        return n[Attrs.DEPTH]

    def height(n):
        if nodetype(n) != "leaf" and n[Attrs.HEIGHT] == 0:
            if n[Attrs.LEFT] != -1:
                lh = height(nodes[n[Attrs.LEFT]])
            else:
                lh = -1

            if n[Attrs.RIGHT] != -1:
                rh = height(nodes[n[Attrs.RIGHT]])
            else:
                rh = -1
            n[Attrs.HEIGHT] = max(lh, rh) + 1
        return n[Attrs.HEIGHT]

    for node in nodes:
        node[Attrs.DEPTH] = depth(node)
        node[Attrs.HEIGHT] = height(node)


def degree(node):
    if node[Attrs.LEFT] != -1 and node[Attrs.RIGHT] != -1:
        return 2
    elif node[Attrs.LEFT] != -1:
        return 1
    elif node[Attrs.RIGHT] != -1:
        return 1
    else:
        return 0


def nodetype(node):
    if node[Attrs.PARENT] == -1:
        return "root"
    elif node[Attrs.LEFT] == -1 and node[Attrs.RIGHT] == -1:
        return "leaf"
    else:
        return "internal node"


def print_tree(ns):
    parents(ns)
    depth_and_heights(ns)

    for nid, n in enumerate(ns):
        print(("node {}: parent = {}, sibling = {}, degree = {}, " +
               "depth = {}, height = {}, {}").format(nid,
                                                     n[Attrs.PARENT],
                                                     n[Attrs.SIBLING],
                                                     degree(n),
                                                     n[Attrs.DEPTH],
                                                     n[Attrs.HEIGHT],
                                                     nodetype(n)))


def run():
    n = int(input())
    nodes = [None] * n

    for i in range(n):
        nodeid, *attrs = [int(i) for i in input().split()]
        attrs.extend([-1, -1, 0, 0])
        nodes[nodeid] = attrs

    print_tree(nodes)


if __name__ == '__main__':
    run()