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:
import sys

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

    def printInfo(self):
        print "node {0.id}: parent = {0.parent.id}, sibling = {0.sibling}, degree = {0.degree}, depth = {0.depth}, height = {0.height}, {0.type}".format(self)

def buildTree(id, nodeList, depth):
    leftId, rightId = nodeList[id][0], nodeList[id][1]
    if leftId == -1 and rightId == -1:
        dummy = Node(-1, None, None, 0, 0, "")
        return Node(id, dummy, dummy, 0, depth, "leaf")
    degree = 0
    if leftId == -1:
        left = Node(-1, None, None, 0, 0, "")
    else:
        left = buildTree(leftId, nodeList, depth + 1)
        degree += 1
    if rightId == -1:
        right = Node(-1, None, None, 0, 0, "")
    else:
        right = buildTree(rightId, nodeList, depth + 1)
        degree += 1
    node = Node(id, left, right, degree, depth, "internal node")

    node.left.parent = node
    node.left.sibling = node.right.id
    node.right.parent = node
    node.right.sibling = node.left.id
    node.height = max(node.left.height, node.right.height) + 1
    return node

def tree2linear(node, list):
    list[node.id] = node
    if node.left.id != -1:
        tree2linear(node.left, list)
    if node.right.id != -1:
        tree2linear(node.right, list)

if __name__ == "__main__":
    lines = sys.stdin.readlines()
    N = int(lines[0])
    del lines[0]

    nodeList = [[]] * N
    sum = N * (N - 1) / 2
    for line in lines:
        line = map(int, line.split())
        id, children = line[0], line[1:]
        nodeList[id] = children
        for child in children:
            if child == -1:
                continue
            sum -= child

    root = buildTree(sum, nodeList, 0)
    root.type = "root"
    root.parent = Node(-1, None, None, 0, 0, "")

    nodeList = [0] * N
    tree2linear(root, nodeList)
    for node in nodeList:
        node.printInfo()

Submission status: Accepted

Solution code:
import sys

class Node:
    def __init__(self):
        self.id = id
        self.parent = -1
        self.sibling = -1
        self.type = "leaf"

    def printInfo(self):
        print "node {0.id}: parent = {0.parent}, sibling = {0.sibling}, degree = {0.degree}, depth = {0.depth}, height = {0.height}, {0.type}".format(self)

def setTree(id, tree, depth):
    tree[id].depth = depth
    height = degree = 0
    for i in range(2):
        child = tree[id].children[i]
        if child != -1:
            degree += 1
            tree[child].parent = id
            tree[child].sibling = tree[id].children[~i]
            height = max(setTree(child, tree, depth + 1) + 1, height)
    tree[id].height = height
    tree[id].degree = degree
    if height != 0:
        tree[id].type = "internal node"

    return height

if __name__ == "__main__":
    lines = sys.stdin.readlines()
    N = int(lines[0])
    del lines[0]

    tree = []
    for i in range(N):
        tree.append(Node())

    root = N * (N - 1) / 2
    for line in lines:
        info = map(int, line.split())
        tree[info[0]].children = info[1:]
        tree[info[0]].id = info[0]
        for i in tree[info[0]].children:
            if i != -1:
                root -= i

    setTree(root, tree, 0)
    tree[root].type = "root"

    for node in tree:
        node.printInfo()

Submission status: Accepted

Solution code:
from functools import reduce
from collections import namedtuple
Node = namedtuple('Node', ['parent', 'children'])
 
class my_binary_tree:
    def __init__(self, N=[]):
        self.T = {}
        for ni in N: self.addNode(ni)
 
    def addNode(self, n):
        p = self.T.get(n[0],Node(-1,[-1,-1])).parent
        self.T[n[0]] = Node(p,n[1:])
        for c in n[1:]:
            if c > -1:  
                cc = self.T.get(c,Node(-1,[-1,-1])).children
                self.T[c] = Node(n[0],cc)
 
    def getParent(self, i): return self.T[i].parent
 
    def getChildren(self, i): return self.T[i].children
 
    def getDepth(self, i):
        if self.T[i].parent == -1: return 0
        return self.getDepth(self.T[i].parent) + 1
 
    def getHeight(self, i):
        c0 = self.T[i].children[0]
        c1 = self.T[i].children[1]
        if c0 + c1 == -2: return 0
        return max( ( 0 if c0 == -1 else self.getHeight(c0) ), \
                    ( 0 if c1 == -1 else self.getHeight(c1) ) )\
               + 1
 
    def getDegree(self, i):
        return int(self.T[i].children[0] != -1) + \
               int(self.T[i].children[1] != -1)
 
    def getNodeType(self, i):
        if self.T[i].parent == -1        : return 'root'
        if sum(self.T[i].children) == -2 : return 'leaf'
        return 'internal node'
 
    def getSibling(self, i):
        p = self.T[i].parent
        if p == -1: return -1
        return sum(self.T[p].children) - i
 
    def getIdList(self): return sorted(self.T.keys())
 
  
if __name__=='__main__':
    n = int(input())
    N = [None]*n
    for i in range(n): N[i] = list(map(int,input().split()))
    tree = my_binary_tree(N)
      
    for i in tree.getIdList():        
        print("node {0}: parent = {1}, sibling = {2}, degree = {3}, depth = {4}, height = {5}, {6}".format(\
                i, tree.getParent(i), tree.getSibling(i), tree.getDegree(i), tree.getDepth(i), tree.getHeight(i), tree.getNodeType(i)))

Submission status: Accepted

Solution code:
def print_node(i, node):
    parent = -1 if node[1] == None else node[1]
    degree = len([x for x in node[0] if x != -1])
    sibling = -1 if node[2] == None else node[2]
    depth = node[3]
    height = node[4]
    t = 'root' if parent == -1 else 'leaf' if height == 0 else 'internal node'
    ans = "node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}".format(i, parent, sibling, degree, depth, height, t)
    print(ans)

n = int(input())

root = set([x for x in range(n)])
T = [None] * n
for x in range(n):
    i, l, r = list(map(int, input().split()))

    # children, parent, sibling, depth, height
    T[i] = [[l, r], None, None, None, None]
    root -= set([l, r])

def set_info(i, depth):
    node = T[i]
    node[3] = depth
    l = None
    r = None
    if node[0][0] != -1:
        l = T[node[0][0]]
        l[1] = i
        set_info(node[0][0], depth + 1)
    if node[0][1] != -1:
        r = T[node[0][1]]
        r[1] = i
        set_info(node[0][1], depth + 1)
    if l != None and r != None:
        l[2] = node[0][1]
        r[2] = node[0][0]

    node[4] = height(i)

def height(i):
    node = T[i]
    l = node[0][0]
    r = node[0][1]
    lh = None
    rh = None
    h = None
    if l != -1:
        lh = height(l)
    if r != -1:
        rh = height(r)
    if lh != None and rh != None:
        h = max(lh, rh)
    elif lh != None:
        h = lh
    elif rh != None:
        h = rh
    if h == None:
        return 0
    else:
        return 1 + h


r = root.pop()
T[r][1] = -1
set_info(r, 0)

for i, n in enumerate(T):
    print_node(i, n)

Submission status: Accepted

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

class Node(object):
    def __init__(self, N):
        self.parent = [-1 for i in range(N)]
        self.left = [-1 for i in range(N)]
        self.right = [-1 for i in range(N)]
        self.depth = [-1 for i in range(N)]
        self.sibling = [-1 for i in range(N)]
        self.height = [0 for i in range(N)]
        self.degree = [0 for i in range(N)]

    def set_depth(self, u):
        d, U = 0, u
        while T.parent[u] is not -1:
            u = T.parent[u]
            d += 1
        self.depth[U] = d

    def set_height(self, u):
        h1 = h2 = 0
        if self.left[u] is not -1:
            h1 = self.set_height(self.left[u]) + 1
        if self.right[u] is not -1:
            h2 = self.set_height(self.right[u]) + 1
        
        self.height[u] = max(h1, h2)
        return max(h1, h2)
            

N = int(input())

# create node
T = Node(N)

# set data
for j in range(N):
    A = [int(i) for i in input().split()]

    # left???right????±????
    T.left[A[0]] = A[1]
    T.right[A[0]] = A[2]
    
    # parent???degree????±????
    for u in A[1:]:
        if u is not -1:
            T.parent[u] = A[0]
            T.degree[A[0]] += 1
            
    # sibling????±????
    if (A[1] is not -1) and (A[2] is not -1):
        T.sibling[A[1]], T.sibling[A[2]] = A[2], A[1]

# set depth
for i in range(N):
    T.set_depth(i)

# set height
T.set_height(T.parent.index(-1))

# ??????
for i in range(N):
    # ?????????????¨?????????????
    if T.parent[i] is -1:
        node = "root"
    elif T.left[i] is -1 and T.right[i] is -1:
        node = "leaf"
    else:
        node = "internal node"

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

Submission status: Accepted

Solution code:
#coding:UTF-8
def depth(leaf,A,d):
    for i in range(len(A)):
        if A[i][1]==leaf or A[i][2]==leaf:
            return depth(A[i][0],A,d+1)
    return d

def height(n,A,h):
    if n[1]!=-1 or n[2]!=-1:
        return max(height(A[n[1]],A,h+1),height(A[n[2]],A,h+1))
    return h

def BT(A,n):
    for i in range(n):
        p=0
        dep=0
        deg=0
        sib=0
        hei=0
        t=""
        if A[i][1]!=-1 and A[i][2]!=-1:
            deg=2
        elif A[i][1]!=-1 or A[i][2]!=-1:
            deg=1
        else:
            deg=0
        if A[i][1]==-1 and A[i][2]==-1 and n>1:
            t="leaf"
            deg=0
            dep=depth(A[i][0],A,dep)
            hei=height(A[i],A,hei)
            for j in range(len(A)):
                if A[i][0]==A[j][1]:
                    sib=A[j][2]
                    break
                elif A[i][0]==A[j][2]:
                    sib=A[j][1]
                    break
            for j in range(len(A)):
                if A[j][2]==A[i][0] or A[j][1]==A[i][0]:
                    p=A[j][0]
                    break
        else:
            hei=height(A[i],A,hei)
            for j in range(len(A)):
                if A[i][0]==A[j][1]:
                    sib=A[j][2]
                    break
                elif A[i][0]==A[j][2]:
                    sib=A[j][1]
                    break
            dep=depth(A[i][0],A,dep)
            if dep==0:
                sib=-1
                p=-1
                t="root"
            else:
                for j in range(len(A)):
                    if A[j][2]==A[i][0] or A[j][1]==A[i][0]:
                        p=A[j][0]
                        t="internal node"
                        break
        
        print("node "+str(A[i][0])+": parent = "+str(p)+", sibling = "+str(sib)+", degree = "+str(deg)+", depth = "+str(dep)+", height = "+str(hei)+", "+t)

if __name__=="__main__":
    n=int(input())
    A=[]
    for i in range(n):
        A.append(list(map(int,input().split(" "))))
    for i in range(n):
        minj=i
        for j in range(i,n):
            if A[j][0]<A[minj][0]:
                minj=j
        A[i],A[minj]=A[minj],A[i]
    BT(A,n)

Submission status: Accepted

Solution code:
#http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_7_B&lang=jp
def cal_depth(binary_tree, target_index, depth, parent, sibling):
    if target_index == -1:
        return 0
    binary_tree[target_index]["depth"] = depth
    binary_tree[target_index]["parent"] = parent
    binary_tree[target_index]["sibling"] = sibling
    height_left = cal_depth(binary_tree, binary_tree[target_index]["left"], depth + 1, target_index, binary_tree[target_index]["right"])
    height_right = cal_depth(binary_tree, binary_tree[target_index]["right"], depth + 1, target_index, binary_tree[target_index]["left"])
    height = max(height_left, height_right)
    binary_tree[target_index]["height"] = height
    return height + 1

def solve(node_data, node_num):
    binary_tree = [{"left":-1, "right":-1, "depth":0, "parent":-1, "sibling":-1, "height":0, "degree":0} for a in range(node_num)]
    root_index = sum([i for i in range(node_num)])
    for node in node_data:
        binary_tree[node[0]]["left"] =  node[1]
        binary_tree[node[0]]["right"] =  node[2]

        if not node[1] == -1:
            root_index -= node[1]
            binary_tree[node[0]]["degree"] += 1
        if not node[2] == -1:
            root_index -= node[2]
            binary_tree[node[0]]["degree"] += 1
            
    cal_depth(binary_tree, root_index, 0, -1,-1)
    return binary_tree

def main():
    node_num = int(input())
    node_data = [[int(a) for a in input().split()] for i in range(node_num)]
    binary_tree = solve(node_data, node_num)

    for i, node in enumerate(binary_tree):
        node_type = "root"
        if node["left"] == -1 and node["right"] == -1 and not node["parent"] == -1:
            node_type = "leaf"
        elif not node["parent"] == -1:
            node_type = "internal node"
        print("node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}".format(i, node["parent"], node["sibling"], node["degree"], node["depth"], node["height"], node_type))
if __name__ == "__main__":
    main()

Submission status: Accepted

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


import sys


class Node(object):
    def __init__(self):
        # init node as a single leaf node.
        self.parent = -1
        self.type = 'leaf'
        self.depth = 0
        self.children = []
        self.degree = 0
        self.sibling = -1
        self.height = 0


def get_depth(v, depth=0):
    if not v.children:
        # print('rt', v.parent, v.depth, depth)
        v.depth = depth
        return v.depth
    v.depth = depth
    # print('out', v.parent, v.depth, v.children, depth)
    if v.children[0] != -1:
        get_depth(node_list[v.children[0]], depth + 1)

    if v.children[1] != -1:
        get_depth(node_list[v.children[1]], depth + 1)
    return v.depth


def get_height(v):
    h1, h2 = 0, 0

    # leaf's height is 0, children: []
    if not v.children:
        return 0

    if v.children[0] != -1:
        h1 = get_height(node_list[v.children[0]]) + 1

    if v.children[1] != -1:
        h2 = get_height(node_list[v.children[1]]) + 1

    v.height = max(h1, h2)
    return v.height


def generate_tree(_array):
    # add info of each node of a ordered tree
    for each in _array:
        idx, *children = [int(x) for x in each]
        # assert len(children) == 2
        if children != [-1, -1]:
            node_list[idx].type = 'internal node'
            node_list[idx].children = children
            node_list[idx].degree = 1 if (-1 in children) else 2
        else:
            # node is leaf as default, children: []
            continue

        for child_idx in children:
            # non-existent node: no parent or sibling
            if child_idx == -1:
                continue
            node_list[child_idx].parent = idx
            node_list[child_idx].sibling = sum(children) - child_idx

    root_idx = [i for i, x in enumerate(node_list) if x.parent == -1][0]
    node_list[root_idx].type = 'root'

    # add node depth info -- using DFS
    get_depth(node_list[root_idx])
    get_height(node_list[root_idx])

    return node_list


def print_result(_node):
    print('parent = ' + str(_node.parent) + ',', end=' ')
    print('sibling = ' + str(_node.sibling) + ',', end=' ')
    print('degree = ' + str(_node.degree) + ',', end=' ')
    print('depth = ' + str(_node.depth) + ',', end=' ')
    print('height = ' + str(_node.height) + ',', end=' ')
    print(_node.type)
    return None


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    array_length = int(_input[0])
    array = list(map(lambda x: x.split(), _input[1:]))
    # assert len(array) == array_length

    node_list = [Node() for _ in range(array_length)]
    ans = generate_tree(_array=array)
    for key, node in enumerate(ans):
        print('node ' + str(key) + ':', end=' ')
        print_result(_node=node)

Submission status: Accepted

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

"""
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

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
"""

import sys


class Node(object):
    def __init__(self):
        # init node as a single leaf node.
        self.parent = -1
        self.type = 'leaf'
        self.depth = 0
        self.children = []
        self.degree = 0
        self.sibling = -1
        self.height = 0


def get_depth(v, depth=0):
    if not v.children:
        # set leaf's depth
        v.depth = depth
        return v.depth

    v.depth = depth

    left_child_idx = v.children[0]
    right_child_idx = v.children[1]
    if left_child_idx != -1:
        get_depth(node_list[left_child_idx], depth + 1)

    if right_child_idx != -1:
        get_depth(node_list[right_child_idx], depth + 1)
    return v.depth


def get_height(v):
    h1, h2 = 0, 0
    # leaf's height is always 0, children: []
    if not v.children:
        return 0

    left_child_idx = v.children[0]
    right_child_idx = v.children[1]
    if left_child_idx != -1:
        h1 = get_height(node_list[left_child_idx]) + 1

    if right_child_idx != -1:
        h2 = get_height(node_list[right_child_idx]) + 1

    v.height = max(h1, h2)
    return v.height


def generate_tree(_array):
    # add info of each node of a ordered tree
    for each in _array:
        idx, *children = [int(x) for x in each]
        # assert len(children) == 2
        if children != [-1, -1]:
            node_list[idx].type = 'internal node'
            node_list[idx].children = children
            node_list[idx].degree = 1 if (-1 in children) else 2
        else:
            # node is leaf as default, children: []
            continue

        for child_idx in children:
            # non-existent node: no parent or sibling
            if child_idx == -1:
                continue
            node_list[child_idx].parent = idx
            node_list[child_idx].sibling = sum(children) - child_idx

    root_idx = [i for i, x in enumerate(node_list) if x.parent == -1][0]
    root_node = node_list[root_idx]
    root_node.type = 'root'

    # add node depth and height info -- using DFS
    get_depth(root_node)
    get_height(root_node)

    return node_list


def print_result(_node):
    print('parent = ' + str(_node.parent) + ',', end=' ')
    print('sibling = ' + str(_node.sibling) + ',', end=' ')
    print('degree = ' + str(_node.degree) + ',', end=' ')
    print('depth = ' + str(_node.depth) + ',', end=' ')
    print('height = ' + str(_node.height) + ',', end=' ')
    print(_node.type)
    return None


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    array_length = int(_input[0])
    array = list(map(lambda x: x.split(), _input[1:]))
    # assert len(array) == array_length

    node_list = [Node() for _ in range(array_length)]
    ans = generate_tree(_array=array)
    for key, node in enumerate(ans):
        print('node ' + str(key) + ':', end=' ')
        print_result(_node=node)

Submission status: Accepted

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

"""
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

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
"""

import sys


class Node(object):
    def __init__(self):
        # init node as a single leaf node.
        self.parent = -1
        self.type = 'leaf'
        self.depth = 0
        self.children = []
        self.degree = 0
        self.sibling = -1
        self.height = 0
        self.index = -1


def get_depth(v, depth=0):
    if not v.children:
        # set leaf's depth
        v.depth = depth
        return v.depth

    v.depth = depth

    left_child_idx = v.children[0]
    right_child_idx = v.children[1]
    if left_child_idx != -1:
        get_depth(node_list[left_child_idx], depth + 1)

    if right_child_idx != -1:
        get_depth(node_list[right_child_idx], depth + 1)
    return v.depth


def get_height(v):
    h1, h2 = 0, 0
    # leaf's height is always 0, children: []
    if not v.children:
        return 0

    left_child_idx = v.children[0]
    right_child_idx = v.children[1]
    if left_child_idx != -1:
        h1 = get_height(node_list[left_child_idx]) + 1

    if right_child_idx != -1:
        h2 = get_height(node_list[right_child_idx]) + 1

    v.height = max(h1, h2)
    return v.height


def generate_tree(_array):
    # add info of each node of a ordered tree
    for each in _array:
        idx, *children = [int(x) for x in each]
        # assert len(children) == 2 and idx >= 0
        node_list[idx].index = idx
        if children != [-1, -1]:
            node_list[idx].type = 'internal node'
            node_list[idx].children = children
            node_list[idx].degree = 1 if (-1 in children) else 2
        else:
            # node is leaf as default, children: []
            continue

        for child_idx in children:
            # non-existent node: no parent or sibling
            if child_idx == -1:
                continue
            node_list[child_idx].parent = idx
            node_list[child_idx].sibling = sum(children) - child_idx

    root_idx = [i for i, x in enumerate(node_list) if x.parent == -1][0]
    root_node = node_list[root_idx]
    root_node.type = 'root'

    # add node depth and height info -- using DFS
    get_depth(root_node)
    get_height(root_node)

    return node_list


def print_result(_node):
    print('node ' + str(_node.index) + ':', end=' ')
    print('parent = ' + str(_node.parent) + ',', end=' ')
    print('sibling = ' + str(_node.sibling) + ',', end=' ')
    print('degree = ' + str(_node.degree) + ',', end=' ')
    print('depth = ' + str(_node.depth) + ',', end=' ')
    print('height = ' + str(_node.height) + ',', end=' ')
    print(_node.type)
    return None


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    array_length = int(_input[0])
    array = list(map(lambda x: x.split(), _input[1:]))
    # assert len(array) == array_length

    node_list = [Node() for _ in range(array_length)]
    ans = generate_tree(_array=array)
    for node in ans:
        print_result(_node=node)

Submission status: Accepted

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

"""
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

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
"""

import sys


class Node(object):
    def __init__(self):
        # init node as a single leaf node.
        self.parent = -1
        self.type = 'leaf'
        self.depth = 0
        self.children = []
        self.degree = 0
        self.sibling = -1
        self.height = 0
        self.index = -1


def get_depth(v, depth=0):
    if not v.children:
        # set leaf's depth
        v.depth = depth
        return v.depth

    v.depth = depth

    left_child_idx = v.children[0]
    right_child_idx = v.children[1]
    if left_child_idx != -1:
        get_depth(node_list[left_child_idx], depth + 1)

    if right_child_idx != -1:
        get_depth(node_list[right_child_idx], depth + 1)
    return v.depth


def get_height(v):
    h1, h2 = 0, 0
    # leaf's height is always 0, children: []
    if not v.children:
        return 0

    left_child_idx = v.children[0]
    right_child_idx = v.children[1]
    if left_child_idx != -1:
        h1 = get_height(node_list[left_child_idx]) + 1

    if right_child_idx != -1:
        h2 = get_height(node_list[right_child_idx]) + 1

    v.height = max(h1, h2)
    return v.height


def generate_tree(_array):
    # add info of each node of a ordered tree
    for each in _array:
        idx, *children = [int(x) for x in each]
        # assert len(children) == 2 and idx >= 0
        node_list[idx].index = idx
        if children != [-1, -1]:
            node_list[idx].type = 'internal node'
            node_list[idx].children = children
            node_list[idx].degree = 1 if (-1 in children) else 2
        else:
            # node is leaf as default, children: []
            continue

        for child_idx in children:
            # non-existent node: no parent or sibling
            if child_idx == -1:
                continue
            node_list[child_idx].parent = idx
            node_list[child_idx].sibling = sum(children) - child_idx

    root_idx = [x.index for x in node_list if x.parent == -1][0]
    root_node = node_list[root_idx]
    root_node.type = 'root'

    # add node depth and height info -- using DFS
    get_depth(root_node)
    get_height(root_node)

    return node_list


def print_result(_node):
    print('node ' + str(_node.index) + ':', end=' ')
    print('parent = ' + str(_node.parent) + ',', end=' ')
    print('sibling = ' + str(_node.sibling) + ',', end=' ')
    print('degree = ' + str(_node.degree) + ',', end=' ')
    print('depth = ' + str(_node.depth) + ',', end=' ')
    print('height = ' + str(_node.height) + ',', end=' ')
    print(_node.type)
    return None


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    array_length = int(_input[0])
    array = list(map(lambda x: x.split(), _input[1:]))
    # assert len(array) == array_length

    node_list = [Node() for _ in range(array_length)]
    ans = generate_tree(_array=array)
    for node in ans:
        print_result(_node=node)