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:
def det_par_sib_deg(nodes):
    n = len(nodes)
    parent = [-1] * n
    sibling = [-1] * n
    degree = [0] * n
    
    for i in range(n):
        p = nodes[i][0]
        l = nodes[i][1]
        r = nodes[i][2]
        if l==-1 and r==-1:
            degree[i] = 0
        elif l!=-1 and r==-1:
            parent[l] = p
            degree[i] = 1
        elif l==-1 and r!=-1:
            parent[r] = p
            degree[i] = 1
        else:
            parent[l] = parent[r] = p
            sibling[l] = r
            sibling[r] = l
            degree[i] = 2
    
    return parent, sibling, degree

def get_root(parent):
    n = len(parent)
    for i in range(n):
        if parent[i]==-1:
            return i

def det_types(root,nodes,degree):
    n = len(nodes)
    types = [""] * n
    for i in range(n):
        if degree[i]==0:
            types[i] = "leaf"
        else:
            types[i] = "internal node"
    types[root] = "root"
    return types

def get_child(num,nodes,degree):
    deg = degree[num]
    if deg==2:
        return deg, [nodes[num][1], nodes[num][2]]
    if deg==1:
        if nodes[num][1]==-1:
            return deg, [nodes[num][2]]
        else:
            return deg, [nodes[num][1]]
    if deg==0:
        return deg, []

def get_leaves(nodes,types):
    n = len(nodes)
    leaves = []
    for i in range(n):
        if types[i]=="leaf":
            leaves.append(i)
    return leaves

def det_height_depth(root,nodes,parent,types):
    n = len(nodes)
    height = [0] * n
    depth = [0] * n
    
    leaves = get_leaves(nodes,types)    
    for leaf in leaves:
        branch = [leaf]
        h = 1
        p = parent[leaf]
        while p!=-1:
            branch.append(p)
            if h>height[p]:
                height[p] = h
            p = parent[p]
            h += 1
        for i,node in enumerate(branch):
            depth[node] = (h-1) - i
        
    return height, depth

# def det_depth(root,nodes,parent,types,height):
#     n = len(nodes)
#     depth = [0] * n
    
#     leaves = get_leaves(nodes,types)
    
#     for leaf in leaves:
#         h = 1
#         p = parent[leaf]
#         branch = [leaf, p]
#         while p!=-1:
#             p = parent[p]
#             branch.append(p)
#             h += 1
#         for node in branch:
#             depth[node] = (h - 1) - height[node]
        
#     return depth

def print_res(n, nodes):
    parent, sibling, degree = det_par_sib_deg(nodes)
    root = get_root(parent)
    types = det_types(root,nodes,degree)
    height, depth = det_height_depth(root,nodes,parent,types)
    for i in range(n):
        num = nodes[i][0]        
        print("node " + str(num) + \
              ": parent = " + str(parent[i]) + \
              ", sibling = " + str(sibling[i]) + \
              ", degree = " + str(degree[i]) + \
              ", depth = " + str(depth[i]) + \
              ", height = " + str(height[i]) + \
              ", " + types[i] )

if __name__ == "__main__":
    n = int(input())
    nodes = [[]] * n
    for i in range(n):
        node = list(map(int, input().split()))
        nodes[node[0]] = node
    print_res(n,nodes)

Submission status: Accepted

Solution code:
if __name__ == '__main__':
    import sys
    input = sys.stdin.readline

    from collections import defaultdict

    NIL = -1

    n = int(input())

    T = defaultdict(lambda: {'left':NIL, 'right':NIL, 'parent':NIL})
    D = {}
    H = {}

    for _ in range(n):
        u, left, right = map(int, input().split())
        T[u]['left'] = left
        T[u]['right'] = right
        if left != NIL:
            T[left]['parent'] = u
        if right != NIL:
            T[right]['parent'] = u

    def set_depth(u, d):
        if u == NIL:
            return
        D[u] = d
        set_depth(T[u]['left'], d+1)
        set_depth(T[u]['right'], d+1)

    def set_height(u):
        h1 = 0
        h2 = 0
        if T[u]['left'] != NIL:
            h1 = set_height(T[u]['left'])+1
        if T[u]['right'] != NIL:
            h2 = set_height(T[u]['right'])+1
        height = max(h1, h2)
        H[u] = height
        return height

    for u, value in T.items():
        if value['parent'] == NIL:
            root = u
            break

    set_depth(root, 0)
    set_height(root)

    # 節点uの兄弟を返す
    def get_sibling(u):
        if T[u]['parent'] == NIL:
            return NIL
        if T[T[u]['parent']]['left'] != u:  # and 以降なくても問題ない
            return T[T[u]['parent']]['left']
        if T[T[u]['parent']]['right'] != u:  # and 以降なくても問題ない
            return T[T[u]['parent']]['right']
        return NIL

    for u in range(n):
        value = T[u]
        parent = value['parent']
        sibling = get_sibling(u)
        deg = 0
        if T[u]['left'] != NIL:
            deg += 1
        if T[u]['right'] != NIL:
            deg += 1
        if value['parent'] == NIL:
            type = 'root'
        elif value['left'] == NIL and value['right'] == NIL:
            type = 'leaf'
        else:
            type = 'internal node'
        depth = D[u]
        height = H[u]
        print('node ' + str(u) + ': ', end='')
        print('parent = ' + str(parent) +', ', end='')
        print('sibling = ' + str(sibling) + ', ', end='')
        print('degree = ' + str(deg) + ', ', end='')
        print('depth = ' + str(depth) + ', ', end='')
        print('height = ' + str(height) + ', ', end='')
        print(type)

Submission status: Accepted

Solution code:
N = int(input())
nodes = [[-1,-1,-1] for i in range(N)]

for k in range(N):
    i,l,r = map(int,input().split())
    nodes[i][1] = l
    nodes[i][2] = r
    if l != -1:
        nodes[l][0] = i
    if r != -1:
        nodes[r][0] = i

#print(nodes)

sib = [-1 for i in range(N)]

for i in range(N):
    if nodes[i][1] != -1 and nodes[i][2] != -1:
        sib[nodes[i][1]] = nodes[i][2]
        sib[nodes[i][2]] = nodes[i][1]

#print(sib)

deg = [0 for i in range(N)]

for i in range(N):
    c = 0
    if nodes[i][1] != -1:
        c += 1
    if nodes[i][2] != -1:
        c += 1
    deg[i] = c

#print(deg)

dep = [-1 for i in range(N)]

def getDepth(node,node_id):
    d = 0
    while node[node_id][0] != -1:
        node_id = node[node_id][0]
        d += 1
    return d

for i in range(N):
    dep[i] = getDepth(nodes,i)

#print(dep)


hei = [0 for i in range(N)]
for i in range(N):
    h = 0
    node_id = i
    while nodes[node_id][0] != -1:
        hei[node_id] = max(hei[node_id], h)
        node_id = nodes[node_id][0]
        h += 1
    hei[node_id] = max(hei[node_id], h)

#print(hei)


typ = [-1 for i in range(N)]

for i in range(N):
    if nodes[i][0] == -1:
        typ[i] = 'root'
    elif deg[i] == 0:
        typ[i] = 'leaf'
    else:
        typ[i] = 'internal node'

for i in range(N):
    print('node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'.format(i,nodes[i][0],sib[i],deg[i],dep[i],hei[i],typ[i]))

Submission status: Accepted

Solution code:
if __name__ == "__main__":
    parent, children, depths, sibling, heights = {}, {}, {}, {}, {}
    n = int(input())
    for _ in range(n):
        i, left, right = input().split()
        if left == "-1" and right == "-1":
            children[i] = None
            continue
        if left == "-1" or right == "-1":
            child = left if right == "-1" else right
            children[i] = [child]
        else:
            children[i] = [left, right]
        for child in children[i]:
            parent[child] = i
    
    root = (set(children) - set(parent)).pop()
    parent[root] = "-1"
    sibling[root] = "-1"
    
    def get_degree(i):
        if children[i] is None:
            return 0
        return len(children[i])

    def get_type(i):
        if parent[i] == "-1":
            return "root"
        if children[i] is None:
            return "leaf"
        return "internal node"
    
    def set_depth(i, depth):
        depths[i] = depth
        if children[i] is not None:
            for child in children[i]:
                set_depth(child, depth+1)

    def set_sibling(i, s):
        sibling[i] = s
        childs = children[i]
        if childs is not None:
            if len(childs) == 1:
                set_sibling(childs[0], "-1")
            else:
                set_sibling(childs[0], childs[1])
                set_sibling(childs[1], childs[0])
    
    def set_height(i):
        if children[i] is None:
            heights[i] = 0
            return 0
        childs = children[i]
        if len(childs) == 1:
            heights[i] = set_height(childs[0])+1
            return heights[i]
        heights[i] = max(set_height(childs[0]), set_height(childs[1]))+1
        return heights[i]

    set_depth(root, 0)
    set_sibling(root, "-1")
    set_height(root)
    for i in map(str, range(n)):
        print("node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}".format(i, parent[i], sibling[i], get_degree(i), depths[i], heights[i], get_type(i)))

Submission status: Accepted

Solution code:
# coding: utf-8
n = int(input())
chd = [[] for i in range(n)]
node = [[-1, -1, 0, 0, 0, 'leaf'] for i in range(n)]
root = -1


def putDepth(nodenum, d):
    node[nodenum][3] = d
    if node[nodenum][2] > 0:
        node[nodenum][5] = 'internal node'
        for i in chd[nodenum]:
            putDepth(i, d + 1)
    if node[nodenum][0] == -1:
        node[nodenum][5] = 'root'


def putHeight(nodenum):
    h1 = 0
    h2 = 0
    if node[nodenum][2] > 0:
        h1 = putHeight(chd[nodenum][0]) + 1
    if node[nodenum][2] == 2:
        h2 = putHeight(chd[nodenum][1]) + 1
    node[nodenum][4] = max(h1, h2)
    return node[nodenum][4]

for i in range(n):
    idx, left, right = map(int, input().split())
    if left >= 0:
        chd[idx].append(left)
        node[left][0] = idx
        node[idx][2] += 1
    if right >= 0:
        chd[idx].append(right)
        node[right][0] = idx
        node[idx][2] += 1
    if node[idx][2] == 2:
        node[left][1] = right
        node[right][1] = left

for i in range(n):
    if node[i][0] == -1:
        root = i
        putDepth(root, 0)
        break

putHeight(root)

for i in range(n):
    print(f'node {i}: parent = {node[i][0]}, sibling = {node[i][1]}, '\
          f'degree = {node[i][2]}, depth = {node[i][3]}, height = '\
          f'{node[i][4]}, {node[i][5]}')

Submission status: Accepted

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

d = {}
def get_all_depth(t, u, p):
    d[u] = p
    if t[u].right is not None:
        get_all_depth(t, t[u].right, p+1)
    if t[u].left is not None:
        get_all_depth(t, t[u].left, p+1)

h = {}
def get_all_height(t, u):
    left, right = 0, 0
    if t[u].left is not None:
        left = get_all_height(t, t[u].left) + 1
    if t[u].right is not None:
        right = get_all_height(t, t[u].right) + 1
    tmp = max(left, right)
    h[u] = tmp
    return tmp

def get_sibling(t, u):
    par = t[u].parent
    if par is None:
        return -1
    left, right = t[par].left, t[par].right
    if left == u:
        if right is not None:
            return right
    elif left is not None:
        return left
    return -1

n = int(input())
t = {k: Node(None, None, None) for k in range(n)}
for _ in range(n):
    tmp = list(map(int, input().split()))
    if tmp[1] != -1:
        t[tmp[1]].parent = tmp[0] # 親
        t[tmp[0]].left = tmp[1] # 左の子
    if tmp[2] != -1:
        t[tmp[2]].parent = tmp[0] # 親
        t[tmp[0]].right = tmp[2] # 右の子

for node in range(n):
    if t[node].parent is None:
        get_all_depth(t, node, 0)
        get_all_height(t, node)
        break

for node in range(n):
    node_type = "internal node" if t[node].left is not None or t[node].right is not None else "leaf"
    if t[node].parent is None:
        node_type = "root"
        parent = -1
    else:
        parent = t[node].parent
    sibling = get_sibling(t, node)
    deg = 0
    if t[node].left is not None:
        deg += 1
    if t[node].right is not None:
        deg += 1
    print(  f"node {node}: parent = {parent}, sibling = {sibling}, "
            f"degree = {deg}, depth = {d[node]}, height = {h[node]}, {node_type}")

Submission status: Accepted

Solution code:
from collections import deque

class binaryNode:
    def __init__(self):
        self.num=-1
        self.parent=-1
        self.brother=-1
        self.child=[]
        self.degree=-1
        self.depth=-1
        self.high=-1
        self.type="-1"


n=int(input())
nodes=[binaryNode() for _ in range(n)]

for _ in range(n):
    idx,left,right=map(int,input().split())
    nodes[idx].num=idx
    child=[]
    if(left!=-1):
        nodes[left].parent=idx
        nodes[left].brother=right
        child.append(left)

    if(right!=-1):
        nodes[right].parent=idx
        nodes[right].brother=left
        child.append(right)

    nodes[idx].child=child
    nodes[idx].degree=len(child)

root_id=-1
for i in range(n):
    if(nodes[i].parent==-1):
        root_id=i
        break

q=deque()
q.append([root_id,0])
while(len(q)>0):
    qi=q.popleft()
    idx=qi[0]
    nodes[idx].depth=qi[1]
    children=nodes[idx].child

    if(nodes[idx].parent==-1):
        nodes[idx].type="root"
    elif(nodes[idx].degree==0):
        nodes[idx].type="leaf"
        nodes[idx].high=0
    else:
        nodes[idx].type="internal node"

    for c in children:
        q.append([c,qi[1]+1])

q.append(root_id)
while(len(q)>0):
    idx=q.popleft()
    children=nodes[idx].child
    children_high=[]
    for c in children:
        if(nodes[c].high==-1):
            q.append(c)
        else:
            children_high.append(nodes[c].high)

    if(len(children)==len(children_high)):
        if(len(children_high)==0):
            nodes[idx].high=0
        else:
            nodes[idx].high=max(children_high)+1
    else:
        q.append(idx)



for i in range(n):
    print("node "+str(i)+": parent = "+str(nodes[i].parent)+", sibling = "+str(nodes[i].brother)+", degree = "+str(nodes[i].degree)+", depth = "+str(nodes[i].depth)+", height = "+str(nodes[i].high)+", "+nodes[i].type)

Submission status: Accepted

Solution code:
class Node:
    def __init__(self, id):
        self.id = id
        self.type = ''
        self.depth = 0
        self.height = 0
        self.parent = -1
        self.sibling = -1
        self.degree = 0
        
        self.left = -1
        self.right = -1
def walk_tree(node, depth, parent):
    if node == None:
        return 0
    if node.left == -1 and node.right == -1:
        node.type = 'leaf'
        node.degree = 0
    elif node.left == -1 and node.right > -1:
        node.type = 'internal node'
        node.degree = 1
        nodes[node.right].sibling = -1
    elif node.left > -1 and node.right == -1:
        node.type = 'internal node'
        node.degree = 1
        nodes[node.left].sibling = -1
    elif node.left > -1 and node.right > -1:
        node.type = 'internal node'
        node.degree = 2
        nodes[node.left].sibling = node.right
        nodes[node.right].sibling = node.left
    node.depth = depth
    node.parent = parent
    height_from_left = walk_tree(nodes.get(node.left), depth+1, node.id)
    height_from_right = walk_tree(nodes.get(node.right), depth+1, node.id)
    height = max(height_from_left, height_from_right)
    
    node.height = height
    height += 1
    return height

n = int(input())
nodes = {}
for _ in range(n):
    id, left, right = [int(x) for x in input().split(' ')]
    node = Node(id)
    node.left = left
    node.right = right
    nodes[id] = node
is_child_table = {node_id:False for node_id in range(n)}
for id in nodes:
    if nodes[id].left > -1:
        is_child_table[nodes[id].left] = True
    if nodes[id].right > -1:
        is_child_table[nodes[id].right] = True
root_id = [node_id for node_id in is_child_table.keys() if is_child_table[node_id] == False][0]
root_node = nodes[root_id]
walk_tree(root_node, 0, -1)
root_node.type = 'root'
for id in range(len(nodes)):
    print("node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}".format(id,
                                                                                                nodes[id].parent,
                                                                                                nodes[id].sibling,
                                                                                                nodes[id].degree,
                                                                                                nodes[id].depth,
                                                                                                nodes[id].height,
                                                                                                nodes[id].type))

Submission status: Accepted

Solution code:
n = int(input())

rt = {}

sl = [[-1 for i in range(3)] for i in range(n)]

for i in range(n):
  id, *s = list(map(int, input().split()))
  if s[0] >= 0 and s[1] >= 0:
    for j in s:
      rt[j] = id
    sl[s[0]][0] = s[1]
    sl[s[1]][0] = s[0]
    sl[id][1] = 2
  elif s[0] >= 0 and s[1] == -1:
    rt[s[0]] = id
    sl[id][1] = 1
  elif s[1] >= 0 and s[0] == -1:
    rt[s[1]] = id
    sl[id][1] = 1

p = [[] for i in range(n)]

for i in range(n):
  p[i] = [i]
  while True:
    try:
      p[i].append(rt[p[i][-1]])
    except:
      break

for i in range(n):
  for j in range(n):
    if i in p[j]:
      sl[i][2] = max(sl[i][2], p[j].index(i))

for i in range(n):
  print("node " + str(i) + ": parent = ", end = "")
  if len(p[i]) == 1 and n == 1:
    print("-1, sibling = -1, degree = 0, depth = 0, height = 0, root")
  elif len(p[i]) == 1 and n > 1:
    print("-1, sibling = -1, degree = " + str(sl[i][1]) + ", depth = 0, height = " + str(sl[i][2]) + ", root")
  else:
    if sl[i][1] == -1:
      print(str(p[i][1]) + ", sibling = " + str(sl[i][0]) + ", degree = 0, depth = " + str(len(p[i])-1) + ", height = 0" +", leaf")
    else:
      print(str(p[i][1]) + ", sibling = " + str(sl[i][0]) + ", degree = " + str(sl[i][1]) + ", depth = " + str(len(p[i])-1) + ", height = " + str(sl[i][2]) +", internal node")

Submission status: Accepted

Solution code:
def tree(s,pls):
	dep[s] += pls
	pls += 1
	if main[s][1] != -1:
		ju1 = tree(main[s][1],pls)
		ju1 += 1
	else:
		ju1 = 0
		hei[s] = 0
		
	if main[s][2] != -1:
		ju2 = tree(main[s][2],pls)
		ju2 += 1
	else:
		ju2 = 0
		hei[s] = 0


	if ju1 > ju2:
		ju = ju1
	else:
		ju = ju2

	del ju1
	del ju2

	#print(str(s) + ":" + str(ju))

	if ju > hei[s]:
		hei[s] = ju
	return ju

def sib(m):
	b = main[m][0]
	if b == -1:
		return -1
	elif m == main[b][1]:
		return main[b][2]
	else :
		return main[b][1]

def deg(w):
	r = 2
	if main[w][1] == -1:
		r -= 1
	if main[w][2] == -1:
		r -= 1
	
	return r



n = int(input())
main = [[-1] * 1 for i in range(n+1)]
for i in range(n):
	a = input().split()
	for j in range(1,3):
		main[int(a[j])][0] = int(a[0])
		main[int(a[0])].append(int(a[j]))
	#print(main)

del a

dep = [-1] * n
hei = [-1] * n


for i in range(n):
	if main[i][0] == -1:
		hei[i] = tree(int(i),1)
		break


for i in range(n):
	print("node " + str(i) + 
		": parent = " + str(main[i][0]) +
		", sibling = " + str(sib(i)) +
		", degree = " + str(deg(i)) +
		", depth = " + str(dep[i]) + 
		", height = " + str(hei[i]) ,end='')
	if main[i][0] == -1:
		print(", root")
	elif main[i][1] == -1 and main[i][2] == -1:
		print(", leaf")
	else:
		print(", internal node")

#print(main)

Submission status: Accepted

Solution code:
class Node:
    
    def __init__(self, parent = -1, left = -1, right = -1):
        self.parent = parent
        self.left = left
        self.right = right
    
    def get_degree(self):
        d = 0
        if self.left != -1:
            d += 1
        if self.right != -1:
            d += 1
        return d

class BinaryTree:
    
    def __init__(self, size):
        self.tree = [Node() for i in range(N)]
    
    def set(self, node_id, left, right):
        self.tree[node_id].left = left
        self.tree[node_id].right = right

        if left != -1:
            self.tree[left].parent = node_id
        if right != -1:
            self.tree[right].parent = node_id
    
    def get_depth(self, node_id):
        d = 0
        while self.tree[node_id].parent != -1:
            d += 1
            node_id = self.tree[node_id].parent
        return d
    
    def get_height(self, node_id):
        h_left = h_right = 0
        if self.tree[node_id].left != -1:
            h_left = self.get_height(self.tree[node_id].left) + 1
        if self.tree[node_id].right != -1:
            h_right = self.get_height(self.tree[node_id].right) + 1
        
        return max(h_left, h_right)
    
    def get_sibling(self, node_id):
        
        if self.tree[node_id].parent == -1:
            return -1
        
        parent_id = self.tree[node_id].parent
        parent = self.tree[parent_id]
        
        if parent.left != -1 and parent.left != node_id:
            return parent.left
        if parent.right != -1 and parent.right != node_id:
            return parent.right
        
        return -1
    
    def get_node_type(self, node_id):
        node = self.tree[node_id]
        
        if node.parent == -1:
            return 'root'
        
        if node.left == -1 and node.right == -1:
            return 'leaf'
        
        return 'internal node'
    
    def print(self):
        for i in range(len(self.tree)):
            node = self.tree[i]
            node_id = i
            parent = node.parent
            sibling = self.get_sibling(node_id)
            degree = node.get_degree()
            depth = self.get_depth(node_id)
            height = self.get_height(node_id)
            node_type = self.get_node_type(node_id)
            print('node %d: parent = %d, sibling = %d, degree = %d, depth = %d, height = %d, %s' % (node_id, parent, sibling, degree, depth, height, node_type))
            
N = int(input())

binary_tree = BinaryTree(N)

for _ in range(N):
    node_id, left, right = list(map(int, input().split()))
    binary_tree.set(node_id, left, right)

binary_tree.print()

Submission status: Accepted

Solution code:
class Node:
    def __init__(self, parent, left, right):
        self.parent = parent
        self.left = left
        self.right = right
        self.sibling=-1
        self.degree=2
        self.height=None

    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_height(self):
        height = 0
        height2 = 0

        if self.right != -1:
            t = Nodes[self.right]
            height =t.get_height()+1

        if self.left != -1:
            t2 = Nodes[self.left]
            height2=t2.get_height()+1
            # height2 += 1

        self.height=max(height,height2)
        return self.height

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

    def get_degree(self):
        degree = 0
        if self.left != -1:
            degree += 1
        if self.right != -1:
            degree += 1
        return degree

def decode_node_data(n):
    '''
    n...受け取る文字列、一行ずつ
    一行ずつ、文字列からノードに変化する
    '''
    global Nodes
    num_of_elem = len(n)
    if num_of_elem < 2:
        raise ValueError
    elif num_of_elem == 2:  # leaf
        pass

    else:
        id, left,right = list(map(int,n))
        # まず、一人目の子供をとりあえず左に格納する
        Nodes[id].left = left
        if left!=-1:
            Nodes[left].sibling=right
            Nodes[left].parent=id
        
        Nodes[id].right = right
        if right !=-1 :
            Nodes[right].sibling=left
            Nodes[right].parent=id

MAX_NODES = 100001
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()
        p=Nodes[node_id]

        print('''node {0}: parent = {1}, sibling = {2}, degree = {3}, depth = {4}, height = {5}, {6}'''.format(
            node_id, p.parent,p.sibling,p.get_degree(), p.get_depth(), p.get_height(), type))

Submission status: Accepted

Solution code:
"""
根付き木を構成する
"""
import copy

class Node:
    def __init__(self):
        self.parent = -1
        self.depth = 0
        self.children = []

#空の木の構成
#node_idをインデックスに持たせる
n = int(input())
nodes = []
for _ in range(n):
    node = Node()
    nodes.append(node)

def getDepth(node_id):
    d = 0
    target = nodes[node_id]
    while target.parent != -1:
        d += 1
        tmp_num = target.parent
        target = nodes[tmp_num]
    return d

def getParent(node_id):
    target = nodes[node_id]
    return target.parent

def getDegree(node_id):
    target = nodes[node_id]
    count = 0
    if target.children[0] != -1:
        count += 1
    if target.children[1] != -1:
        count += 1
    return count

def getType(node_id):
    target = nodes[node_id]
    if target.parent == -1:
        return 'root'
    elif target.children[0] == -1 and target.children[1] == -1:
        return 'leaf'
    else:
        return 'internal node'

def getSibling(node_id):
    target = nodes[node_id]
    if not target.parent == -1:
        brother_list = copy.copy(nodes[target.parent].children)
        brother_list.remove(node_id)
        return brother_list[0]
    else:
        return -1

def getChildren(node_id):
    target= nodes[node_id]
    return target.children

def getHeight(node_id, h): #このhに結果を保持してく
    target = nodes[node_id]
    h1 = 0
    h2 = 0
    if target.children[0] != -1:
        h1 = getHeight(target.children[0], h)+1
    if target.children[1] != -1:
        h2 = getHeight(target.children[1], h)+1
    h = max(h1, h2)
    return h



#木の構成
for i in range(n):
    l = list(map(int, input().split()))
    node_id = l[0]

    for j in range(2):
        try:
            child = l[1+j] #l[1+j]というのは子供の番号
            nodes[node_id].children.append(child) 
            if not child == -1:
                nodes[child].parent = node_id #子一人当たり親は必ず一人
        except:
            pass #エラー回避
    else:
        pass #子がいないとき


for i in range(n):
    ans = 'node '+str(i)+': ' +\
          'parent = '+str(getParent(i))+', ' +\
          'sibling = '+str(getSibling(i))+', ' +\
          'degree = '+str(getDegree(i))+', ' +\
          'depth = '+str(getDepth(i))+', '+\
          'height = '+str(getHeight(i, h=0))+', ' +\
           getType(i)
    print(ans)

Submission status: Accepted

Solution code:
import sys

n = int(input())

nodes = [[-1, -1, -1] for _ in range(n)]

depths = [None for _ in range(n)]

heights = [None for _ in range(n)]

for _ in range(n):
    nid, left, right = list(map(int, sys.stdin.readline().split()))
    nodes[nid][1] = left
    nodes[nid][2] = right

    if left != -1: nodes[left][0] = nid
    if right != -1: nodes[right][0] = nid

def set_depths_heights(nid, p):
    if nid == -1:
        return -1
    depths[nid] = p
    heights[nid] = max(
                    set_depths_heights(nodes[nid][1], p + 1),
                    set_depths_heights(nodes[nid][2], p + 1)) + 1
    return heights[nid]

for nid in range(n):
    if nodes[nid][0] == -1:
        set_depths_heights(nid, 0)

for nid, node in enumerate(nodes):
    pid = node[0]
    sibling = -1 if pid == -1 else (nodes[pid][1] if nodes[pid][1] != nid else nodes[pid][2])
    degree = (0 if node[1] == -1 else 1) + (0 if node[2] == -1 else 1)
    depth = depths[nid]
    height = heights[nid]
    n_type = 'root' if pid == -1 else 'leaf' if height == 0 else 'internal node'

    print('node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'.format(nid, pid, sibling, degree, depth, height, n_type))