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:
N = int(input())

binary_tree = [{"parent": -1, "sibling": -1} for _ in range(N)]
for _ in range(N):
    node_input = input()
    id, left, right = map(int, node_input.split())

    binary_tree[id]["left"] = left
    binary_tree[id]["right"] = right

    degree = 0
    if left != -1:
        degree += 1
        binary_tree[left]["parent"] = id
        binary_tree[left]["sibling"] = right
    if right != -1:
        degree += 1
        binary_tree[right]["parent"] = id
        binary_tree[right]["sibling"] = left
    binary_tree[id]["degree"] = degree


def measure_depth_and_height(id, depth):
    H[id] = max(H[id], depth)

    parent_id = binary_tree[id]["parent"]
    if parent_id == -1:
        return depth

    return measure_depth_and_height(parent_id, depth+1)

D = [0 for i in range(N)]
H = [0 for i in range(N)]
for id in range(N):
    depth = measure_depth_and_height(id, 0)
    D[id] = depth


def get_type(node):
    if node["parent"] == -1:
        return "root"
    if node["degree"] == 0:
        return "leaf"
    if node["parent"] == -1:
        return "root"
    return "internal node"

for id in range(N):
    node = binary_tree[id]
    parent_id = node["parent"]
    sibling_id = node["sibling"]
    degree = node["degree"]
    node_type = get_type(node)
    print("node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}".format(id, parent_id, sibling_id, degree, D[id], H[id], node_type))

Submission status: Accepted

Solution code:
N = int(input())


binary_tree = [{"parent": -1, "sibling": -1} for _ in range(N)]
for _ in range(N):
    node_input = input()
    id, left, right = map(int, node_input.split())

    binary_tree[id]["left"] = left
    binary_tree[id]["right"] = right

    if left != -1:
        binary_tree[left]["parent"] = id
    if right != -1:
        binary_tree[right]["parent"] = id


def set_depth(id, depth):
    if id == -1:
        return

    D[id] = depth
    set_depth(binary_tree[id]["left"], depth+1)
    set_depth(binary_tree[id]["right"], depth+1)

def set_height(id):
    h1, h2 = 0, 0
    if binary_tree[id]["left"] != -1:
        h1 = set_height(binary_tree[id]["left"]) + 1
    if binary_tree[id]["right"] != -1:
        h2 = set_height(binary_tree[id]["right"]) + 1
    H[id] = max(h1, h2)
    return H[id]


D = [0 for i in range(N)]
H = [0 for i in range(N)]
for id in range(N):
    if binary_tree[id]["parent"] == -1:
        set_depth(id, 0)
        set_height(id)


def get_sibling(id):
    parent_id = node["parent"]
    if parent_id == -1:
        return -1
    if binary_tree[parent_id]["left"] != id:
        return binary_tree[parent_id]["left"]
    else:
        return binary_tree[parent_id]["right"]

def get_degree(node):
    degree = 0
    if node["left"] != -1:
        degree += 1
    if node["right"] != -1:
        degree += 1
    return degree

def get_type(node, dgree):
    if node["parent"] == -1:
        return "root"
    if degree == 0:
        return "leaf"
    return "internal node"

for id in range(N):
    node = binary_tree[id]
    parent_id = node["parent"]
    sibling_id = get_sibling(id)
    degree = get_degree(node)
    node_type = get_type(node, degree)
    print("node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}".format(id, parent_id, sibling_id, degree, D[id], H[id], node_type))

Submission status: Accepted

Solution code:
N = int(input())

binary_tree = [{"parent": -1, "sibling": -1} for _ in range(N)]
for _ in range(N):
    node_input = input()
    id, left, right = map(int, node_input.split())

    binary_tree[id]["left"] = left
    binary_tree[id]["right"] = right

    degree = 0
    if left != -1:
        degree += 1
        binary_tree[left]["parent"] = id
        binary_tree[left]["sibling"] = right
    if right != -1:
        degree += 1
        binary_tree[right]["parent"] = id
        binary_tree[right]["sibling"] = left
    binary_tree[id]["degree"] = degree


def measure_depth_and_height(id, depth):
    H[id] = max(H[id], depth)

    parent_id = binary_tree[id]["parent"]
    if parent_id == -1:
        return depth

    return measure_depth_and_height(parent_id, depth+1)

D = [0 for i in range(N)]
H = [0 for i in range(N)]
for id in range(N):
    depth = measure_depth_and_height(id, 0)
    D[id] = depth


def get_type(node):
    if node["parent"] == -1:
        return "root"
    if node["degree"] == 0:
        return "leaf"
    return "internal node"

for id in range(N):
    node = binary_tree[id]
    parent_id = node["parent"]
    sibling_id = node["sibling"]
    degree = node["degree"]
    node_type = get_type(node)
    print("node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}".format(id, parent_id, sibling_id, degree, D[id], H[id], node_type))

Submission status: Accepted

Solution code:
N = int(input())


binary_tree = [{"parent": -1} for _ in range(N)]
for _ in range(N):
    node_input = input()
    id, left, right = map(int, node_input.split())

    binary_tree[id]["left"] = left
    binary_tree[id]["right"] = right

    if left != -1:
        binary_tree[left]["parent"] = id
    if right != -1:
        binary_tree[right]["parent"] = id


def set_depth(id, depth):
    if id == -1:
        return

    D[id] = depth
    set_depth(binary_tree[id]["left"], depth+1)
    set_depth(binary_tree[id]["right"], depth+1)

def set_height(id):
    h1, h2 = 0, 0
    if binary_tree[id]["left"] != -1:
        h1 = set_height(binary_tree[id]["left"]) + 1
    if binary_tree[id]["right"] != -1:
        h2 = set_height(binary_tree[id]["right"]) + 1
    H[id] = max(h1, h2)
    return H[id]


D = [0 for i in range(N)]
H = [0 for i in range(N)]
for id in range(N):
    if binary_tree[id]["parent"] == -1:
        set_depth(id, 0)
        set_height(id)
        break



def get_sibling(id):
    parent_id = node["parent"]
    if parent_id == -1:
        return -1
    if binary_tree[parent_id]["left"] != id:
        return binary_tree[parent_id]["left"]
    else:
        return binary_tree[parent_id]["right"]

def get_degree(node):
    degree = 0
    if node["left"] != -1:
        degree += 1
    if node["right"] != -1:
        degree += 1
    return degree

def get_type(node, dgree):
    if node["parent"] == -1:
        return "root"
    if degree == 0:
        return "leaf"
    return "internal node"

for id in range(N):
    node = binary_tree[id]
    parent_id = node["parent"]
    sibling_id = get_sibling(id)
    degree = get_degree(node)
    node_type = get_type(node, degree)
    print("node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}".format(id, parent_id, sibling_id, degree, D[id], H[id], node_type))

Submission status: Accepted

Solution code:
N = int(input())

class Node():
    def __init__(self, parent = -1, left = -1, right = -1):
        self.parent = parent
        self.left = left
        self.right = right

binary_tree = [Node() for _ in range(N)]
for _ in range(N):
    node_input = input()
    id, left, right = map(int, node_input.split())

    binary_tree[id].left = left
    binary_tree[id].right = right

    if left != -1:
        binary_tree[left].parent = id
    if right != -1:
        binary_tree[right].parent = id


def set_depth(id, depth):
    if id == -1:
        return

    D[id] = depth
    set_depth(binary_tree[id].left, depth+1)
    set_depth(binary_tree[id].right, depth+1)

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


D = [0 for i in range(N)]
H = [0 for i in range(N)]
for id in range(N):
    if binary_tree[id].parent == -1:
        set_depth(id, 0)
        set_height(id)
        break



def get_sibling(id):
    parent_id = node.parent
    if parent_id == -1:
        return -1
    if binary_tree[parent_id].left != id:
        return binary_tree[parent_id].left
    else:
        return binary_tree[parent_id].right

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

def get_type(node, dgree):
    if node.parent == -1:
        return "root"
    if degree == 0:
        return "leaf"
    return "internal node"

for id in range(N):
    node = binary_tree[id]
    parent_id = node.parent
    sibling_id = get_sibling(id)
    degree = get_degree(node)
    node_type = get_type(node, degree)
    print("node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}".format(id, parent_id, sibling_id, degree, D[id], H[id], node_type))

Submission status: Accepted

Solution code:
class Node:
	def __init__(self, id):
		self.id = id
		self.parent_id = -1
		self.left = -1
		self.right = -1
		self.sibling = -1
		self.depth = -1
		self.height = -1
	def get_type(self):
		if self.parent_id == -1:
			return 'root'
		elif self.left == -1 and self.right == -1:
			return 'leaf'
		return 'internal node'
	def get_degree(self):
		ret = 0
		if self.left != -1: ret += 1
		if self.right != -1: ret += 1
		return ret
	def __str__(self):
		strNode = 'node ' + str(self.id) + ': '
		strNode += 'parent = ' + str(self.parent_id) + ', '
		strNode += 'sibling = ' + str(self.sibling) + ', '
		strNode += 'degree = ' + str(self.get_degree()) + ', '
		strNode += 'depth = ' + str(self.depth) + ', '
		strNode += 'height = ' + str(self.height) + ', '
		strNode += self.get_type()
		return strNode

def calc_depth(nodes):
	stack = []
	for i in range(len(nodes)):
		if nodes[i].parent_id == -1:
			nodes[i].depth = 0
			stack.append(nodes[i].id)
			break
	while len(stack) != 0:
		node = nodes[stack.pop()]
		if node.left != -1:
			nodes[node.left].depth = node.depth + 1
			stack.append(node.left)
		if node.right != -1:
			nodes[node.right].depth = node.depth + 1
			stack.append(node.right)

def calc_height(nodes):
	stack = []
	for i in range(len(nodes)):
		if nodes[i].left == -1 and nodes[i].right == -1:
			nodes[i].height = 0
			stack.append(nodes[i].id)
	while len(stack) != 0:
		node = nodes[stack.pop()]
		if node.parent_id != -1:
			parent = nodes[node.parent_id]
			parent.height = max(parent.height, node.height + 1)
			stack.append(node.parent_id)

n = int(input())
nodes = [Node(i) for i in range(n)]
for i in range(n):
	id, left, right = map(int, input().split())
	nodes[id].left = left
	nodes[id].right = right
	if left != -1:
		nodes[left].parent_id = id
		nodes[left].sibling = right
	if right != -1:
		nodes[right].parent_id = id
		nodes[right].sibling = left

calc_depth(nodes)
calc_height(nodes)

for i in range(n):
	print(nodes[i])

Submission status: Accepted

Solution code:
from sys import stdin

class Node(object):
    def __init__(self, parent=None, left=None, right=None,
                 name=None, sibling=None, degree=None):
        self.parent = parent
        self.left = left
        self.right = right
        self.name = name
        self.sibling = sibling
        self.degree = degree

def print_nodes(nodes, n):
    def get_depth(nodes, u):
        p = nodes[u].parent
        nonlocal d
        if p != None and p != -1:
            get_depth(nodes, p)
            d += 1
        return d

    def get_height(nodes, u):
        h1 = 0
        h2 = 0
        r = nodes[u].right
        l = nodes[u].left
        if r != -1:
            h1 = get_height(nodes, r) + 1
        if l != -1:
            h2 = get_height(nodes, l) + 1
        return max(h1, h2)

    for i in range(n):
        d = 0
        if nodes[i].parent == None:
            nodes[i].parent = -1
            nodes[i].sibling = -1
            nodes[i].name = "root"
        print("node {0}: parent = {1}, sibling = {2}, degree = {3}, depth = {4}, height = {5}, {6}".format(
               i, nodes[i].parent, nodes[i].sibling, nodes[i].degree, get_depth(nodes, i),
               get_height(nodes, i), nodes[i].name))

def read_binary_tree(nodes, n):
    for _ in range(n):
        i = [int(i) for i in stdin.readline().strip().split()]
        nodes[i[0]].left = i[1]
        nodes[i[0]].right = i[2]
        nodes[i[0]].degree = 0
        if i[1] != -1:
            nodes[i[0]].name = "internal node"
            nodes[i[1]].parent = i[0]
            nodes[i[1]].sibling = i[2]
            nodes[i[0]].degree += 1
        if i[2] != -1:
            nodes[i[0]].name = "internal node"
            nodes[i[2]].parent = i[0]
            nodes[i[2]].sibling = i[1]
            nodes[i[0]].degree += 1
        if i[1] == -1 and i[2] == -1:
            nodes[i[0]].name = "leaf"

n = int(input())
nodes = [Node() for _ in range(n)]
read_binary_tree(nodes, n)
print_nodes(nodes, n)

Submission status: Accepted

Solution code:
from sys import stdin

class Node():
    NIL = -1

    def __init__(self, p=NIL, l=NIL, r=NIL, d=-1, h=-1):
        self.p = p
        self.l = l
        self.r = r
        self.d = d
        self.h = h

    def __repr__(self):
        return "Node({}, {}, {}, {})".format(self.p, self.l, self.r, self.d)

def root_of(T):
    return [u.p for u in T].index(Node.NIL)

def sibling_of(T, id):
    p = T[T[id].p]
    return p.r if p.l == id else p.l

def degree_of(T, id):
    l = 0 if T[id].l == Node.NIL else 1
    r = 0 if T[id].r == Node.NIL else 1
    return l + r

def calc_depth(T):

    def rec(id, depth):
        nonlocal T

        T[id].d = depth
        if T[id].l != Node.NIL:
            rec(T[id].l, depth + 1)
        if T[id].r != Node.NIL:
            rec(T[id].r, depth + 1)

    rec(root_of(T), 0)

def calc_height(T):

    def rec(id):
        nonlocal T

        l = 0 if T[id].l == Node.NIL else rec(T[id].l) + 1
        r = 0 if T[id].r == Node.NIL else rec(T[id].r) + 1
        T[id].h = max(l, r)
        return T[id].h

    rec(root_of(T))

def type_of(T, id):
    if T[id].p == Node.NIL:
        return "root"
    elif T[id].l == Node.NIL and T[id].r == Node.NIL:
        return "leaf"
    else:
        return "internal node"

def read_nodes(T):
    for line in stdin:
        id, l, r = [int(x) for x in line.split()]
        T[id].l = l
        if l != Node.NIL:
            T[l].p = id
        T[id].r = r
        if r != Node.NIL:
            T[r].p = id

def print_nodes(T):
    for id in range(len(T)):
        print("node {}: ".format(id), end="")
        print("parent = {}, ".format(T[id].p), end="")
        print("sibling = {}, ".format(sibling_of(T, id)), end="")
        print("degree = {}, ".format(degree_of(T, id)), end="")
        print("depth = {}, ".format(T[id].d), end="")
        print("height = {}, ".format(T[id].h), end="")
        print(type_of(T, id))

def main():
    n = int(stdin.readline())
    T = [Node() for _ in range(n)]

    read_nodes(T)
    calc_depth(T)
    calc_height(T)
    print_nodes(T)

main()

Submission status: Accepted

Solution code:
n = int(input())
class BiTree():
    def __init__(self, node, left, right):
        self.node = node
        self.left = left
        self.right = right
dali = [0] * n
def inputdata(i):
    node, left, right = list(map(int, input().split()))
    dali[node] = BiTree(node, left, right)
def getParent(i):
    for k in range(n):
        if(dali[k].right == dali[i].node) or (dali[k].left == dali[i].node):
            dali[i].parent = dali[k].node
            return dali[i].parent
    dali[i].parent = -1

    return dali[i].parent
def getDepth(i):
    h = 0
    tmp = dali[i].parent
    while True:
        if tmp == -1:
            dali[i].depth = h
            break
        else:
            tmp = getParent(tmp)
            h += 1


def getHeight(i):  # i == daliの要素番号
    h1 = 0
    h2 = 0
    if dali[i].right != -1:
        h1 = getHeight(dali[i].right) + 1
    if dali[i].left != -1:
        h2 = getHeight(dali[i].left) + 1 
    return max(h1, h2)
def getDegree(i):
    if dali[i].right == -1 and dali[i].left == -1:
        dali[i].deg = 0
    elif dali[i].right == -1 :
        dali[i].deg = 1
    elif dali[i].left == -1:
        dali[i].deg = 1
    else:
        dali[i].deg = 2


def getType(i):
    if dali[i].parent == -1:
        dali[i].type = "root"
    elif dali[i].deg == 0:
        dali[i].type = "leaf"
    else:
        dali[i].type = "internal node"
def getSibling(i):
    if dali[i].type == "root":
        dali[i].sibling = -1
        return 0
    sib = []
    sib.append((dali[dali[i].parent].right))
    sib.append(dali[dali[i].parent].left)
    if sib[0] == dali[i].node:
        dali[i].sibling = sib[1]
    else:
        dali[i].sibling = sib[0]
for j in range(n):
    inputdata(j)
for j in range(n):
    getParent(dali[j].node)
for j in range(n):
    getDepth(dali[j].node)
h1 = 0
h2 = 0
for j in range(n):
    dali[j].height = getHeight(dali[j].node)
    h1 = 0
    h2 = 0
for j in range(n):
    getDegree(dali[j].node)
for j in range(n):
    getType(dali[j].node)
for j in range(n):
    getSibling(dali[j].node)
for j in range((dali[j].node)+1):
    print("node %d: parent = %d, sibling = %d, degree = %d, depth = %d, height = %d, %s" % (dali[j].node, dali[j].parent, dali[j].sibling, dali[j].deg, dali[j].depth, dali[j].height, dali[j].type))

Submission status: Accepted

Solution code:
n = int(input())
deg = [0]*n
child, parent = {}, {}
sib = [None]*n
for i in range(n):
    a = list(map(int, input().split()))
    if a[1] != -1:
        if a[2] == -1:
            child[a[0]] = [a[1]]
            sib[a[1]] = a[2]
            deg[a[0]] = 1
        else:
            child[a[0]] = a[1:]
            sib[a[1]] = a[2]
            sib[a[2]] = a[1]
            deg[a[0]] = 2
        for j in child[a[0]]:
            parent[j] = a[0]
    elif a[2] != -1:
        child[a[0]] = [a[2]]
        sib[a[2]] = a[1]
        deg[a[0]] = 1
        for j in child[a[0]]:
            parent[j] = a[0]
    else:
        child[a[0]] = []

root = (set(child)-set(parent)).pop()
depth = [None]*n
depth[root] = 0
hei = [None]*n
parent[root] = -1
sib[root] = -1

def dfs(s):
    if len(child[s]) == 0:
        hei[s] = 0
        return
    for i in child[s]:
        depth[i] = depth[s] + 1
        dfs(i)
    hei[s] = max(hei[i] for i in child[s]) + 1
    
    
dfs(root)

for i in range(n):
    node_type = 'root' if parent[i] == -1 else 'leaf' if len(child[i]) == 0 else 'internal node'
    print(f'node {i}: parent = {parent[i]}, sibling = {sib[i]}, degree = {deg[i]}, depth = {depth[i]}, height = {hei[i]}, {node_type}')

Submission status: Accepted

Solution code:
def f(n,d):
    t=[f(i,d+1)+1 for i in l[n][1]]
    h=0 if t==[] else max(t)
    c[n][3:3]=[len(l[n][1]),d,h,"root" if d<1 else "leaf" if h<1 else "internal node"]
    return h
m=input()
c=[0]*m
l=sorted([map(int,raw_input().split()) for _ in range(m)])
for i in l:
    n,a,b=i
    if a>=0:c[a]=[a,n,b]
    if b>=0:c[b]=[b,n,a]
    i[1:]=[[j for j in i[1:] if j>=0]]
n=c.index(0)
c[n]=[n,-1,-1]
f(n,0)
for i in c:print "node {0}: parent = {1}, sibling = {2}, degree = {3}, depth = {4}, height = {5}, {6}".format(*i)

Submission status: Accepted

Solution code:
class Tree():
    def __init__(self):
        self.nodes = {}
        self.nodes[-1] = None
    def add_node(self, id):
        if id not in self.nodes:
            self.nodes[id] = Node(id)        
    def add_child(self, parent_id, left_id, right_id):
        self.add_node(parent_id)
        self.add_node(left_id)
        self.add_node(right_id)
        self.nodes[parent_id].add_child(self.nodes[left_id], self.nodes[right_id])
    
class Node():
    def __init__(self, id):
        self.id = id
        self.parent = self.left = self.right = None
        self.depth = self.height = 0

    def add_child(self, left, right):
        self.left = left
        self.right = right
        
        self.update_height()
        
        for child in self.children():
            child.parent = self
            child.update_depth()
    def update_height(self):
        if self.degree():
            self.height = max([child.height + 1 for child in self.children()])
            if self.parent:
                self.parent.update_height()
            
    def update_depth(self):
        self.depth = self.parent.depth + 1
        for child in self.children():
            child.update_depth()
                
    def nodetype(self):
        if self.parent:
            if self.degree():
                return 'internal node'
            else:
                return 'leaf'
        else:
            return 'root'
    def degree(self):
        return len(self.children())
    
    def children(self):
        return [child for child in [self.left, self.right] if child]
    
    def sibling(self):
        if self.parent and self.parent.degree() == 2:
            if self.parent.left == self:
                return self.parent.right.id
            else:
                return self.parent.left.id
        else:
            return -1
        

    def __str__(self):
        return 'node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'.format(
            self.id,
            self.parent.id if self.parent else - 1,
            self.sibling(),
            self.degree(),
            self.depth,
            self.height,
            self.nodetype())
    
tree = Tree()

n = int(input())
for i in range(n):
    id, left, right = map(int, input().split())
    tree.add_child(id, left, right)

for id in tree.nodes:
    if id != -1:
        print(tree.nodes[id])

Submission status: Accepted

Solution code:
# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_7_B
# Rooted Trees
# Result:
import sys

class Node(object):
    def __init__(self, id_):
        super(Node, self).__init__()
        self.id_ = id_
        self.parent = None
        self.left = None
        self.right = None

    def set_child(self, left, right):
        self.left = left
        self.right = right

    def set_parent(self, parent):
        assert self.parent == None
        self.parent = parent

    def sibling(self):
        if self.parent == None: return None
        if self.parent.left == self:
            return self.parent.right
        else:
            return self.parent.left

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

    def depth(self):
        depth = 0
        p = self.parent
        while p != None:
            depth += 1
            p = p.parent
        return depth

    def height(self):
        return self._height(self)

    def _height(self, n):
        assert n != None
        if n.left == None and n.right == None: return 0
        hl = self._height(n.left) + 1 if n.left != None else 0
        hr = self._height(n.right) + 1 if n.right != None else 0
        return hl if hl > hr else hr

    def __str__(self):
        str_ = 'node %d: ' % (self.id_)
        parent_id = self.parent.id_ if self.parent != None else -1
        str_ += 'parent = %d, ' % (parent_id)
        sibling_id = self.sibling().id_ if self.sibling() != None else -1
        str_ += 'sibling = %d, ' % (sibling_id)
        str_ += 'degree = %d, ' % (self.degree())
        str_ += 'depth = %d, ' % (self.depth())
        str_ += 'height = %d, ' % (self.height())
        if self.depth() == 0:
            str_ += 'root'
        elif self.degree() != 0:
            str_ += 'internal node'
        else:
            str_ += 'leaf'
        return str_


nnodes = int(sys.stdin.readline())
nodes = []
for i in range(0, nnodes):
    nodes.append(Node(i))

# set parent and child
for _ in range(0, nnodes):
    vals = sys.stdin.readline().rstrip().split(' ')
    node_id = int(vals[0])
    left_id_ = int(vals[1])
    right_id_ = int(vals[2])
    node = nodes[node_id]
    left_ = nodes[left_id_] if left_id_ != -1 else None
    right_ = nodes[right_id_] if right_id_ != -1 else None
    node.set_child(left_, right_)
    if left_ != None:
        left_.set_parent(node)
    if right_ != None:
        right_.set_parent(node)

for node in nodes:
    print node

Submission status: Accepted

Solution code:
# coding: utf-8
# Here your code !

# coding: utf-8
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 range(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
                #print 'height:', node.height, 'leftheight',nodes[node.left].height,'rightheight',nodes[node.right].height
        dep -= 1
        #print 'height:', node.height, 'leftheight',nodes[node.left].height,'rightheight',nodes[node.right].height
    
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 range(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)