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
# Here your code !

from collections import deque 

class Node:
    def __init__(self):
        self.id = -1
        self.sibling = -1
        self.degree = -1
        self.depth = -1
        self.height = -1
        self.parent = -1
        self.left = -1
        self.right = -1
        self.type = 'root'
        
def find_root_id(nodes):
    for node in nodes:
        if node.parent == -1:
            return node.id
 
def set_depth(rootid, nodes):
    nodes[rootid].depth = 0
    depth = 0
    node = nodes[rootid]
    que = deque()
    que.append(node.left)
    que.append(node.right)
    ref = deque()
    ref.append(-1)
    ref.append(-1)
    if que == ref:
        node.depth = 0
        return 0
    for i in que:
        nodes[i].depth = depth + 1
    depth += 1
    
    while que:
        for i in xrange(len(que)):
            popped = que.popleft()
            l = nodes[popped].left
            r = nodes[popped].right
            if l != -1:
                que.append(nodes[popped].left)
            if r != -1:
                que.append(nodes[popped].right)
        for j in que:
            nodes[j].depth = depth + 1
        depth += 1
    return depth
        
def set_height(rootid, nodes, dep):
    if len(nodes) == 1:
        nodes[0].height=0
    for node in nodes:
        if node.type == 'leaf':
            node.height = 0
            
    while dep > 0:
        for node in nodes:
            if node.depth == dep:
                nodes[node.parent].height = max(nodes[nodes[node.parent].left].height, nodes[nodes[node.parent].right].height) + 1
        dep -= 1
    
def set_degree(nodes):
    for node in nodes:
        node.degree = sum([1 for i in [node.left, node.right] if i != -1])
        
def set_parent(nodes):
    for node in nodes:
        if node.left != -1:
            nodes[node.left].parent = node.id
        if node.right != -1:
            nodes[node.right].parent = node.id
            
def set_sibling(rootid, nodes):
    for node in nodes:
        if node.id != rootid:
            if nodes[node.parent].left == node.id:
                node.sibling = nodes[node.parent].right
            elif nodes[node.parent].right == node.id:
                node.sibling = nodes[node.parent].left
        else:
            pass#root has no sibling
        
def set_type(nodes):
    for node in nodes:
        if node.left == -1 and node.right == -1:
            if node.parent != -1:
                node.type = 'leaf'
        else:
            if node.parent != -1:
                node.type = 'internal node'
    
n = int(raw_input())
nodes = []
for i in xrange(n):
    node = Node()
    ls =  map(int, raw_input().split())
    node.id = ls[0]
    node.left = ls[1]
    node.right = ls[2]
    nodes.append(node)
    
nodes = sorted(nodes, key=lambda node:node.id)

set_degree(nodes)
set_parent(nodes)
rootid = find_root_id(nodes)

set_type(nodes)
set_sibling(rootid, nodes)
dep = set_depth(rootid, nodes)
set_height(rootid, nodes, dep)
for node in nodes:
    print 'node %s: parent = %s, sibling = %s, degree = %s, depth = %s, height = %s, %s'%(node.id, node.parent, node.sibling, node.degree, node.depth, node.height, node.type)

Submission status: Accepted

Solution code:
class Node:
    def __init__(self, id):
        self.id = id
        self.left = None
        self.right = None
        self.sibling = None
        self.degree = 0
        self.parent = None
        self.depth = -1
        self.nodeType = ''

    def __repr__(self):
        return self.__str__()

    def __str__(self):
        parent_id = self.parent.id if self.parent != None else -1
        sibling_id = self.sibling.id if self.sibling != None else -1
        return 'node ' + str(self.id)\
                + ': parent = ' + str(parent_id)\
                + ', sibling = ' + str(sibling_id)\
                + ', degree = ' + str(self.degree)\
                + ', depth = ' + str(self.depth)\
                + ', height = ' + str(self.high)\
                + ', ' + self.get_node_type()

    def set_depth(self, now_depth):
        self.depth = now_depth
        if self.left != None:
            self.left.set_depth(now_depth + 1)

        if self.right != None:
            self.right.set_depth(now_depth + 1)

    def set_high(self):
        if self.left == None and self.right == None:
            self.high = 0
            return 0
        left_high = 0
        right_high = 0
        if self.left != None:
            left_high = self.left.set_high()
        if self.right != None:
            right_high = self.right.set_high()
        self.high = max([left_high, right_high]) + 1
        return self.high

    def get_node_type(self):
        if self.parent == None:
            return 'root'
        elif self.left == None and self.right == None:
            return 'leaf'
        else:
            return 'internal node'

n = int(raw_input())
tree = [Node(i) for i in xrange(n)]
for i in xrange(n):
    line = map(int, raw_input().split())
    id, left_id, right_id = line[0], line[1], line[2]
    if left_id != -1:
        tree[id].left = tree[left_id]
        tree[left_id].parent = tree[id]
        tree[id].degree += 1
    if right_id != -1:
        tree[id].right = tree[right_id]
        tree[right_id].parent = tree[id]
        tree[id].degree += 1
    if left_id != -1 and right_id != -1:
        tree[left_id].sibling = tree[right_id]
        tree[right_id].sibling = tree[left_id]

# find root
root = None
for t in tree:
    if t.parent == None:
        root = t

root.set_depth(0)
root.set_high()

for t in tree:
    print t

Submission status: Accepted

Solution code:
class Node:
    def __init__(self):
        self.parent = -1
        self.sibling = -1


def dfs(v, d=0):
    G[v].depth, G[v].height = d, 0
    if G[v].left != -1:
        G[v].height = max(G[v].height, dfs(G[v].left, d+1) + 1)
    if G[v].right != -1:
        G[v].height = max(G[v].height, dfs(G[v].right, d+1) + 1)
    return G[v].height

N = int(input())
G = [Node() for _ in range(N)]
for _ in range(N):
    idx, *children = [int(x) for x in input().split()]
    G[idx].left, G[idx].right = children
    if G[idx].left != -1 and G[idx].right != -1:
        G[G[idx].left].sibling, G[G[idx].right].sibling = G[idx].right, G[idx].left
    if G[idx].left != -1 or G[idx].right != -1:
        G[idx].type = 'internal node'
    else:
        G[idx].type = 'leaf'
    for child in children:
        if child != -1:
            G[child].parent = idx
root = [i for i, x in enumerate(G) if x.parent == -1][0]
G[root].type = 'root'
dfs(root)
for i, node in enumerate(G):
    print('node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'.format(i, node.parent, node.sibling, (node.left != -1) + (node.right != -1), node.depth, node.height, node.type))

Submission status: Accepted

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

def set_height(u,H):
    h1 = 0
    h2 = 0
    if tree[u].left != -1:
        h1 = set_height(tree[u].left,H) + 1
    if tree[u].right != -1:
        h2 = set_height(tree[u].right,H) + 1
    H[u] = max(h1,h2)
    return H[u]

def set_sibling(u,S):
    if tree[u].parent != -1:
        v = tree[tree[u].parent].left
        if v == u:
            v = tree[tree[u].parent].right
        S[u] = v
    else:
        S[u] = -1
    if tree[u].left != -1:
        set_sibling(tree[u].left, S)
    if tree[u].right != -1:
        set_sibling(tree[u].right, S)

def set_degree(u,D):
    d = 0
    if tree[u].left != -1:
        d += 1
    if tree[u].right != -1:
        d += 1
    D[u] = d
    if tree[u].left != -1:
        set_degree(tree[u].left, D)
    if tree[u].right != -1:
        set_degree(tree[u].right, D)

def set_depth(u,P,d):
    P[u] = d
    if tree[u].left != -1:
        set_depth(tree[u].left, P, d+1)
    if tree[u].right != -1:
        set_depth(tree[u].right, P, d+1)



n = int(raw_input().strip())
tree = {}
for i in range(n):
    nid, left, right = map(int, raw_input().strip().split(' '))
    if not nid in tree: tree[nid] = Node(-1,left,right)
    else:
        tree[nid].left = left
        tree[nid].right = right
    if not left == -1:
        if not left in tree: tree[left] = Node(nid,-1,-1)
        else: tree[left].parent = nid
    if not right == -1:
        if not right in tree: tree[right] = Node(nid,-1,-1)
        else: tree[right].parent = nid

r = -1
for i in range(len(tree)):
    if tree[i].parent == -1:
        r = i
        break

H = {}
set_height(r,H)
S = {}
set_sibling(r,S)
D = {}
set_degree(r,D)
P = {}
set_depth(r,P,0)

for i in range(len(tree)):
    if tree[i].parent == -1:
        t = "root"
    elif tree[i].left == -1 and tree[i].right == -1:
        t = "leaf"
    else:
        t = "internal node"
    print "node %s: parent = %s, sibling = %s, degree = %s, depth = %s, height = %s, %s" % (i, tree[i].parent, S[i], D[i], P[i], H[i], t)

Submission status: Accepted

Solution code:
n = int(input())
tree = [None] * n
root = set(range(n))


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


while n:
    i, l, r = list(map(int, input().split()))
    tree[i] = [l, r] + [None] * 5  # parent, sibling, degree, depth, height
    root -= {l, r}
    n -= 1

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

for i, node in enumerate(tree):
    l, r, p, s, deg, dep, h = node
    print('node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'.format(
        i, p, s, deg, dep, h, 'root' if not dep else 'internal node' if deg else 'leaf'
    ))

Submission status: Accepted

Solution code:
#coding:utf-8
#1_7_B
class Node():
    def __init__(self, node_id):
        self.node_id    =   node_id
        self.parent     =   -1
        self.sibling    =   -1
        self.degree     =   0
        self.depth      =   0
        self.height     =   0
        self.typ        =   'root'
        self.children   =   []

    def set_parent(self, child):
        child.parent = self.node_id
        self.degree += 1
        self.children.append(child)

        if child.degree:
            child.typ = 'internal node'
        else:
            child.typ = 'leaf'

        if self.parent != -1:
            self.typ = 'internal node'

    def set_sibling(self, sibling):
        self.sibling = sibling

def set_depth(tree):
    for node in tree:
        if node.typ == 'root':
            root = node
            break
    queue = []
    queue.extend(root.children)
    while queue:
        node = queue.pop(0)
        node.depth = tree[node.parent].depth + 1
        queue.extend(node.children)

def set_height(tree):
    queue = []
    for node in tree:
        if node.typ == 'leaf':
            queue.append(node)

    while queue:
        leaf = queue.pop(0)
        if leaf.parent != -1 and tree[leaf.parent].height < leaf.height + 1:
            tree[leaf.parent].height = leaf.height + 1
            queue.append(tree[leaf.parent])

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

for i in range(n):
    node_id, left, right = map(int, input().split())
    if left != -1:
        tree[node_id].set_parent(tree[left])
        tree[left].set_sibling(right)
    if right != -1:
        tree[node_id].set_parent(tree[right])
        tree[right].set_sibling(left)

set_depth(tree)
set_height(tree)

for node in tree:
    print("node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}".format(node.node_id, node.parent, node.sibling, node.degree, node.depth, node.height, node.typ))

Submission status: Accepted

Solution code:
#coding:utf-8
#1_7_B
class Node():
    def __init__(self, node_id):
        self.node_id    =   node_id
        self.parent     =   -1
        self.sibling    =   -1
        self.degree     =   0
        self.depth      =   0
        self.height     =   0
        self.typ        =   'root'
        self.children   =   []

    def set_parent(self, child):
        child.parent = self.node_id
        self.degree += 1
        self.children.append(child)

        if child.degree:
            child.typ = 'internal node'
        else:
            child.typ = 'leaf'

        if self.parent != -1:
            self.typ = 'internal node'

    def set_sibling(self, sibling):
        self.sibling = sibling

def set_depth(tree):
    for node in tree:
        if node.typ == 'root':
            root = node
            break
    queue = []
    queue.extend(root.children)
    while queue:
        node = queue.pop(0)
        node.depth = tree[node.parent].depth + 1
        queue.extend(node.children)

def set_height(tree):
    queue = []
    for node in tree:
        if node.typ == 'leaf':
            queue.append(node)
    while queue:
        leaf = queue.pop(0)
        if leaf.parent != -1 and tree[leaf.parent].height < leaf.height + 1:
            tree[leaf.parent].height = leaf.height + 1
            queue.append(tree[leaf.parent])

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

for i in range(n):
    node_id, left, right = map(int, input().split())
    if left != -1:
        tree[node_id].set_parent(tree[left])
        tree[left].set_sibling(right)
    if right != -1:
        tree[node_id].set_parent(tree[right])
        tree[right].set_sibling(left)

set_depth(tree)
set_height(tree)

for node in tree:
    print("node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}".format(node.node_id, node.parent, node.sibling, node.degree, node.depth, node.height, node.typ))

Submission status: Accepted

Solution code:
#coding:utf-8
#1_7_B
class Node():
    def __init__(self, node_id, left, right):
        self.node_id    =   node_id
        self.parent     =   -1
        self.sibling    =   -1
        self.left       =   left
        self.right      =   right
        self.degree     =   0
        self.depth      =   0
        self.height     =   0
        self.typ        =   "leaf"

    def set_attr(self, node_id, parent, sibling, depth):
        if node_id == -1:
            return -1
        self.parent     =   parent
        self.sibling    =   sibling
        self.depth      =   depth
        self.degree     =   (self.left != -1) + (self.right != -1)
        if self.degree:
            self.typ    =   "internal node"
        if self.parent == -1:
            self.typ    =   "root"
        self.height     =   max(tree[self.left].set_attr(self.left, self.node_id, self.right, self.depth + 1), tree[self.right].set_attr(self.right, self.node_id, self.left, self.depth + 1)) + 1
        return self.height

n = int(input())
tree = [None for i in range(n)]
root = set(range(n))

for i in range(n):
    node_id, left, right = map(int, input().split())
    tree[node_id] = Node(node_id, left, right)
    root -= set([left, right])

root_id = root.pop()
tree[root_id].set_attr(root_id, -1, -1, 0)

for node in tree:
    print("node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}".format(node.node_id, node.parent, node.sibling, node.degree, node.depth, node.height, node.typ))

Submission status: Accepted

Solution code:
n = int(raw_input())



FORMAT = ('node {0.id}: parent = {0.parent}, sibling = {0.sibling}, degree = {0.degree}, depth = {0.depth}, height = {0.height}, {0.type}').format

class Node:
    def __init__(self):
        self.id = -1
        self.parent = -1
        self.left = -1
        self.right = -1
        self.sibling = -1
        self.degree = 0
        self.depth = 0
        self.height = 0
        self.type = 'leaf' if self.height == 0 else 'internal node'
        
    def setType(self):
        if self.height == 0 and self.parent != -1:
            self.type = 'leaf'
        elif self.parent == -1:
            self.type = 'root'
        else:
            self.type = 'internal node'

    def __str__(self):
        return FORMAT(self)

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

def setDepth(u, d):#(0,0)
    T[u].depth = d
    if T[u].left == -1 and T[u].right == -1:
        return
    if T[u].left != -1 and T[u].right == -1:
        setDepth(T[u].left, d+1)
    elif T[u].left == -1 and T[u].right != -1:
        setDepth(T[u].right, d+1)
    else:
        setDepth(T[u].left, d+1)
        setDepth(T[u].right, d+1)

T = [Node() for _ in xrange(n)]

for i in xrange(n):
    a = map(int, raw_input().split())
    u = a[0]
    l = a[1]
    r = a[2]
    T[u].id = u
    T[u].left = l  #set child
    T[u].right = r  #set child
    if l != -1 and r != -1:
        T[l].parent = u  #set parent
        T[r].parent = u  #set parent
    elif l != -1 and r == -1:
        T[l].parent = u  #set parent
    elif l == -1 and r != -1:
        T[r].parent = u  #set parent

    if l != -1 and r != -1:
        T[u].degree = 2
        T[l].sibling = r
        T[r].sibling = l
    elif l != -1 and r == -1:
        T[u].degree = 1
    elif  l == -1 and r != -1:
        T[u].degree = 1

N = 0
for i in xrange(n):
    if T[i].parent == -1:
        N = T[i].id

setHeight(T, N)
setDepth(N, 0)


for i in xrange(n):
    T[i].setType()
    print T[i]

Submission status: Accepted

Solution code:
from collections import deque, namedtuple

class BinaryTree:
    def __init__(self, t):
        self.t = t

    def setDepth(self, u, d):
        if u == -1:
            return
        self.t[u] = self.t[u]._replace(d = d)
        self.setDepth(self.t[u].l, d + 1)
        self.setDepth(self.t[u].r, d + 1)

    def setHeight(self, u):
        h1 = 0
        h2 = 0
        if self.t[u].l != -1:
            h1 = self.setHeight(self.t[u].l) + 1
        if self.t[u].r != -1:
            h2 = self.setHeight(self.t[u].r) + 1
        self.t[u] = self.t[u]._replace(h = max(h1, h2))
        return self.t[u].h

    def getSibling(self, u):
        if self.t[u].p == -1:
            return -1
        if self.t[self.t[u].p].l not in (u, -1):
            return self.t[self.t[u].p].l
        if self.t[self.t[u].p].r not in (u, -1):
            return self.t[self.t[u].p].r
        return -1

    def printNode(self, i):
        p_ = self.t[i].p
        s_ = self.getSibling(i)
        deg_ = 0
        if self.t[i].l != -1:
            deg_ += 1
        if self.t[i].r != -1:
            deg_ += 1
        dep_ = self.t[i].d
        h_ = self.t[i].h
        if p_ == -1:
            t_ = "root"
        elif deg_ == 0:
            t_ = "leaf"
        else:
            t_ = "internal node"
        print("node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}".format(i, p_, s_,  deg_, dep_, h_, t_))

if __name__ == '__main__':
    n = int(input().rstrip())
    Node = namedtuple('Node', ['p', 'l', 'r', 'd', 'h'])
    t = [Node(-1, -1, -1, -1, -1)] * n
    r = -1
    for i in range(n):
        v, l, r = [int(i) for i in input().rstrip().split(" ")]
        t[v] = t[v]._replace(l = l, r = r)
        if l != -1:
            t[l] = t[l]._replace(p = v)
        if r != -1:
            t[r] = t[r]._replace(p = v)
    for i in range(n):
        if (t[i].p == -1):
            r = i
    x = BinaryTree(t)
    x.setDepth(r, 0)
    x.setHeight(r)
    for i in range(n):
        x.printNode(i)

Submission status: Accepted

Solution code:
class Node:
    def __init__(self, num, leftChild, rightChild):
        self.id = num
        self.parent = -1
        self.sibling = -1
        self.degree = 0
        self.depth = 0
        self.height = 0
        self.type = 'leaf'
        self.leftChild = leftChild
        self.rightChild = rightChild
        
    def show_info(self):
        print('node {}:'.format(self.id), 'parent = {},'.format(self.parent),
              'sibling = {},'.format(self.sibling),
              'degree = {},'.format(self.degree),
              'depth = {},'.format(self.depth),
              'height = {},'.format(self.height),
              '{}'.format(self.type))


def set_node(i_s):
    num, leftChild, rightChild = list(map(int, i_s.split()))
    node = Node(num, leftChild, rightChild)
    T[num] = node
    T[-1] -= (max(0, leftChild) + max(0, rightChild))


def set_attributes(n_i, parent, sibling, depth):
    node = T[n_i]
    node.parent = parent
    node.sibling = sibling
    node.depth = depth
    if node.leftChild != -1:
        node.degree += 1
        node.type = 'internal node'
        set_attributes(node.leftChild, node.id, node.rightChild, depth + 1)
    if node.rightChild != -1:
        node.degree += 1
        node.type = 'internal node'
        set_attributes(node.rightChild, node.id, node.leftChild, depth + 1)
    if node.leftChild != -1 and node.rightChild != -1:
        node.height = max(T[node.leftChild].height,
                          T[node.rightChild].height) + 1
    elif node.leftChild != -1:
        node.height = T[node.leftChild].height + 1
    elif node.rightChild != -1:
        node.height = T[node.rightChild].height + 1



import sys

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

T = [None] * n

T.append(int(n * (n - 1) / 2))

for x in sys.stdin.readlines():
    set_node(x)

set_attributes(T[-1], -1, -1, 0)

T[T[-1]].type = 'root'

for n in T[:-1]:
    n.show_info()

Submission status: Accepted

Solution code:
"""Binary Trees."""

class Node:
    def __init__(self, num, leftChild, rightChild):
        self.id = num
        self.parent = -1
        self.sibling = -1
        self.degree = 0
        self.depth = 0
        self.height = 0
        self.type = 'leaf'
        self.leftChild = leftChild
        self.rightChild = rightChild
        
    def show_info(self):
        print('node {}:'.format(self.id), 'parent = {},'.format(self.parent),
              'sibling = {},'.format(self.sibling),
              'degree = {},'.format(self.degree),
              'depth = {},'.format(self.depth),
              'height = {},'.format(self.height),
              '{}'.format(self.type))


def set_attributes(n_i, parent, sibling, depth):
    if n_i == -1:
        return -1
    node = T[n_i]
    lc = node.leftChild
    rc = node.rightChild
    node.parent = parent
    node.sibling = sibling
    node.depth = depth
    node.degree = (node.leftChild != -1) + (node.rightChild != -1)
    if lc != -1 or rc != -1:
        node.type = 'internal node'
    node.height = max(set_attributes(lc, n_i, rc, depth + 1),
                      set_attributes(rc, n_i, lc, depth + 1)) + 1
    return node.height



import sys

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

T = [None] * n

rt_n = int(n * (n - 1) / 2)

for x in sys.stdin.readlines():
    num, leftChild, rightChild = list(map(int, x.split()))
    node = Node(num, leftChild, rightChild)
    T[num] = node
    rt_n -= (max(0, leftChild) + max(0, rightChild))

set_attributes(rt_n, -1, -1, 0)

T[rt_n].type = 'root'

for n in T:
    n.show_info()

Submission status: Accepted

Solution code:
"""Binary Trees."""

class Node:
    def __init__(self, num, leftChild, rightChild):
        self.id = num
        self.parent = -1
        self.sibling = -1
        self.degree = 0
        self.depth = 0
        self.height = 0
        self.type = 'leaf'
        self.leftChild = leftChild
        self.rightChild = rightChild
        
    def show_info(self):
        print('node {}:'.format(self.id), 'parent = {},'.format(self.parent),
              'sibling = {},'.format(self.sibling),
              'degree = {},'.format(self.degree),
              'depth = {},'.format(self.depth),
              'height = {},'.format(self.height),
              '{}'.format(self.type))


def set_attributes(n_i, parent, sibling, depth):
    h1 = 0
    h2 = 0
    node = T[n_i]
    lc = node.leftChild
    rc = node.rightChild
    node.parent = parent
    node.sibling = sibling
    node.depth = depth
    if lc != -1:
        node.degree += 1
        node.type = 'internal node'
        h1 = set_attributes(lc, n_i, rc, depth + 1) + 1
    if rc != -1:
        node.degree += 1
        node.type = 'internal node'
        h2 = set_attributes(rc, n_i, lc, depth + 1) + 1
    node.height = max(h1, h2)
    return node.height



import sys

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

T = [None] * n

rt_n = int(n * (n - 1) / 2)

for x in sys.stdin.readlines():
    num, leftChild, rightChild = list(map(int, x.split()))
    node = Node(num, leftChild, rightChild)
    T[num] = node
    rt_n -= (max(0, leftChild) + max(0, rightChild))

set_attributes(rt_n, -1, -1, 0)

T[rt_n].type = 'root'

for n in T:
    n.show_info()

Submission status: Accepted

Solution code:
class BinTree():
    def __init__(self):
        self.parent = -1
        self.left, self.right = -1, -1
        self.sib = -1
        self.dep, self.deg, self.h = 0, 0, 0
        self.state = "internal node"

    def set_node(self, nid, l, r):
        global root
        root -= {l, r}
        self.left, self.right = l, r
        self.deg = (l != -1) + (r != -1)
        if l != -1:
            left = trees[l]
            left.parent = nid
            left.sib = r
        if r != -1:
            right = trees[r]
            right.parent = nid
            right.sib = l

    def set_param(self):
        if self.parent != -1:
            self.dep = trees[self.parent].dep + 1
        if self.deg == 0:
            self.state = "leaf"
        if self.left != -1:
            left = trees[self.left]
            left.set_param()
            self.h = left.h + 1
        if self.right != -1:
            right = trees[self.right]
            right.set_param()
            if self.h <= right.h:
                self.h = right.h + 1
        if self.parent == -1:
            self.state = "root"

    def echo(self, nid):
        print('node {}: parent = {}'.format(nid, self.parent),
              'sibling = {}'.format(self.sib),
              'degree = {}'.format(self.deg),
              'depth = {}'.format(self.dep),
              'height = {}'.format(self.h),
              self.state, sep=', ')

n = int(input())
trees = [BinTree() for _ in range(n)]
root = set(range(n))
for _ in range(n):
    inp = list(map(int, input().split()))
    trees[inp[0]].set_node(*inp)
root = root.pop()
trees[root].set_param()
for i, tree in enumerate(trees):
    tree.echo(i)

Submission status: Accepted

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

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

n = int(raw_input())
node_dic = {}
par_list = [0]*n
sib_list = [0]*n
deg_list = [0]*n
dep_list = [0]*n
hei_list = [0]*n
typ_list = ['']*n
root = 0
for i in range(n):
    root += i
for i in range(n):
    id, left, right = map(int, raw_input().split())
    node_dic[id] = Node_Class(left, right)
#parent
for i in range(n):
    left = node_dic[i].left
    right = node_dic[i].right
    if left > -1:
        par_list[left] = i
        root -= left
    if right > -1:
        par_list[right] = i
        root -= right
par_list[root] = -1
#sibling
for i in range(n):
    left = node_dic[i].left
    right = node_dic[i].right
    if left > -1:
        sib_list[left] = right
    if right > -1:
        sib_list[right] = left
sib_list[root] = -1
#degree
for i in range(n):
    if node_dic[i].left > -1:
        deg_list[i] += 1
    if node_dic[i].right > -1:
        deg_list[i] += 1
#depth
for i in range(n):
    j = i
    while par_list[j] > -1:
        j = par_list[j]
        dep_list[i] += 1
#height
for i in range(n):
    if node_dic[i].left != -1 or node_dic[i].right != -1:
        continue
    j = i
    height = 0
    while par_list[j] > -1:
        j = par_list[j]
        height += 1
        hei_list[j] = max(hei_list[j], height)

#type
for i in range(n):
    if par_list[i] == -1:
        typ_list[i] = typ_list[i] + "root"
    else:
        if node_dic[i].left > -1 or node_dic[i].right > -1:
            typ_list[i] = typ_list[i] + "internal node"
        else:
            typ_list[i] = typ_list[i] + "leaf"
#print
for i in range(n):
    s = "node %d: parent = %d, sibling = %d, degree = %d, depth = %d, height = %d, %s" %(i, par_list[i], sib_list[i], deg_list[i], dep_list[i], hei_list[i], typ_list[i])
    print s