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: Runtime Error

Solution code:
using System;
using System.Collections.Generic;
using System.Text;

namespace ALDS1_7_B
{
    class Node
    {
        public int Parent { get; set; }
        public int Sibling { get; set; }
        public int Degree { get; set; }
        public int Depth { get; set; }
        public int Hight { get; set; }
        public string Type { get; set; }
        public List<int> Children { get; set; }


        public Node()
        {
            Parent = -1;
            Sibling = -1;
            Degree = 0;
            Depth = -1;
            Hight = -1;
            Type = "";
            Children = new List<int>();
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            int i;
            var n = int.Parse(Console.ReadLine());
            var Nodes = new Node[n];
            for (i = 0; i < n; i++) Nodes[i] = new Node();

            for (i = 0; i < n; i++)
            {
                int[] input = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
                int parent = input[0], left = input[1], right = input[2];
                if (left == -1 && right == -1)
                {
                    Nodes[parent].Type = "leaf";
                    Nodes[parent].Hight = 0;
                }
                else if (left == -1 || right == -1)
                {
                    var child = (left > -1) ? left : right;
                    Nodes[parent].Children.Add(child);
                    Nodes[child].Parent = parent;
                    Nodes[parent].Degree = 1;
                }
                else
                {
                    Nodes[parent].Children.Add(right);
                    Nodes[parent].Children.Add(left);

                    Nodes[left].Parent = parent;
                    Nodes[left].Sibling = right;

                    Nodes[right].Parent = parent;
                    Nodes[right].Sibling = left;

                    Nodes[parent].Degree = 2;
                }
            }

            int rootIndex = 0;

            for (i = 0; i < n; i++)
            {
                if (Nodes[i].Parent == -1)
                {
                    Nodes[i].Type = "root";
                    Nodes[i].Depth = 0;
                    rootIndex = i;
                }
                else if (Nodes[i].Type != "leaf")
                {
                    Nodes[i].Type = "internal node";
                }
            }

            var stk = new Stack<Node>();
            var MaxDepth = 0;
            stk.Push(Nodes[rootIndex]);

            while (stk.Count > 0)
            {
                Node temp = stk.Pop();

                foreach (var child in temp.Children)
                {
                    Nodes[child].Depth = temp.Depth + 1;
                    MaxDepth = (Nodes[child].Depth > MaxDepth) ? Nodes[child].Depth : MaxDepth;
                    if (Nodes[child].Children.Count > 0)
                    {
                        stk.Push(Nodes[child]);
                    }
                }

            }

            for (i = 0; i < n; i++)
            {
                if (Nodes[i].Type == "leaf")
                {
                    continue;
                }
                foreach (var child in Nodes[i].Children)
                {
                    if (Nodes[child].Type == "leaf")
                    {
                        continue;
                    }
                }
                Nodes[i].Hight = MaxDepth - Nodes[i].Depth;
            }

            StringBuilder sb = new StringBuilder();
            for (i = 0; i < n; i++)
            {
                sb.AppendLine("node " + i + ": parent = " + Nodes[i].Parent + ", sibling = " + Nodes[i].Sibling + ", degree = " +
                    Nodes[i].Degree + ", depth = " + Nodes[i].Depth + ", height = " + Nodes[i].Hight + ", " + Nodes[i].Type);
            }
            Console.Write(sb);
            Console.ReadLine();
        }
    }

}

Submission status: Runtime Error

Solution code:
using System;
using System.Collections.Generic;
using System.Text;

namespace ALDS1_7_B
{
    class Node
    {
        public int Parent { get; set; }
        public int Sibling { get; set; }
        public int Degree { get; set; }
        public int Depth { get; set; }
        public int Hight { get; set; }
        public string Type { get; set; }
        public List<int> Children { get; set; }


        public Node()
        {
            Parent = -1;
            Sibling = -1;
            Degree = 0;
            Depth = -1;
            Hight = -1;
            Type = "";
            Children = new List<int>();
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            int i;
            var n = int.Parse(Console.ReadLine());
            var Nodes = new Node[n];
            for (i = 0; i < n; i++) Nodes[i] = new Node();

            for (i = 0; i < n; i++)
            {
                int[] input = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
                int parent = input[0], left = input[1], right = input[2];
                if (left == -1 && right == -1)
                {
                    Nodes[parent].Type = "leaf";
                    Nodes[parent].Hight = 0;
                }
                else if (left == -1 || right == -1)
                {
                    var child = (left > -1) ? left : right;
                    Nodes[parent].Children.Add(child);
                    Nodes[child].Parent = parent;
                    Nodes[parent].Degree = 1;
                }
                else
                {
                    Nodes[parent].Children.Add(right);
                    Nodes[parent].Children.Add(left);

                    Nodes[left].Parent = parent;
                    Nodes[left].Sibling = right;

                    Nodes[right].Parent = parent;
                    Nodes[right].Sibling = left;

                    Nodes[parent].Degree = 2;
                }
            }

            int rootIndex = 0;

            for (i = 0; i < n; i++)
            {
                if (Nodes[i].Parent == -1)
                {
                    Nodes[i].Type = "root";
                    Nodes[i].Depth = 0;
                    rootIndex = i;
                }
                else if (Nodes[i].Type != "leaf")
                {
                    Nodes[i].Type = "internal node";
                }
            }

            var stk = new Stack<Node>();
            var MaxDepth = 0;
            stk.Push(Nodes[rootIndex]);

            while (stk.Count > 0)
            {
                Node temp = stk.Pop();

                foreach (var child in temp.Children)
                {
                    Nodes[child].Depth = temp.Depth + 1;
                    MaxDepth = (Nodes[child].Depth > MaxDepth) ? Nodes[child].Depth : MaxDepth;
                    if (Nodes[child].Children.Count > 0)
                    {
                        stk.Push(Nodes[child]);
                    }
                }

            }

            var ParentPushflag = true;
            stk.Push(Nodes[rootIndex]);
            while (stk.Count > 0)
            {
                var node = stk.Pop();
                foreach (var child in node.Children)
                {
                    if (Nodes[child].Hight == -1)
                    {
                        if (ParentPushflag)
                        {
                            stk.Push(node);
                            ParentPushflag = false;
                        }
                        
                        stk.Push(Nodes[child]);
                    }
                    else
                    {
                        node.Hight = (Nodes[child].Hight + 1 > node.Hight) ? Nodes[child].Hight + 1 : node.Hight;
                    }
                }
                ParentPushflag = true;
            }
            

            StringBuilder sb = new StringBuilder();
            for (i = 0; i < n; i++)
            {
                sb.AppendLine("node " + i + ": parent = " + Nodes[i].Parent + ", sibling = " + Nodes[i].Sibling + ", degree = " +
                    Nodes[i].Degree + ", depth = " + Nodes[i].Depth + ", height = " + Nodes[i].Hight + ", " + Nodes[i].Type);
            }
            Console.Write(sb);
            Console.ReadLine();
        }
    }

}

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function
from sys import stdin

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


class Node(object):
    def __init__(self, data):
        self.id = data[0]
        self.parent = -1
        self.sibling = -1
        self.degree = int(data[1] > 0) + int(data[2] > 0)
        self.childs = [i for i in data[1:] if i > 0]
        self.depth = 0
        self.height = -1
        self.type = 'internal node' if self.degree else 'leaf'

    def __str__(self):
        return FORMAT(self)


def calc_depth(tree, i):
    h = 0
    for k, j in enumerate(tree[i].childs):
        tree[j].depth += 1
        tree[j].sibling = tree[i].childs[1-k]
        h = max(h, calc_depth(tree, j))
    if tree[i].type == 'leaf':
        tree[i].height = 0
    else:
        tree[i].height = h
    return tree[i].height + 1


n = int(stdin.readline())
tree = [-1] * n

for _ in range(n):
    node = Node([int(s) for s in stdin.readline().split()])
    parent = tree[node.id]
    tree[node.id] = node
    if isinstance(parent, int):
        tree[node.id].parent = parent
    else:
        tree[node.id].parent = parent.id
    for i in node.childs:
        if isinstance(tree[i], int):
            tree[i] = node.id
        else:
            tree[i].parent = node.id

for i in range(n):
    calc_depth(tree, i)

for node in tree:
    if node.parent == -1:
        node.type = 'root'
    print(node)

Submission status: WA: Presentation Error

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["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: WA: Presentation Error

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:
        dali[i].deg = 0
    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: WA: Presentation Error

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:
        dali[i].deg = 0
    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: WA: Presentation Error

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: WA: Presentation Error

Solution code:
class Node:
    def __init__(self, num, left,  right):
        self.id = num
        self.left = left
        self.right = right
        self.parent = -1
        self.brother = -1
        if self.left== -1 and self.right==-1:
        	self.child = 0
        elif self.left != -1 and self.right!=-1:
        	self.child = 2
        else:
        	self.child = 1
        self.depth = 0
        self.height = 0
        self.type = None

    def show_info(self):
        print('node {0}: parent = {1}, sibling = {2}, degree =  {3}, depth = {4}, height = {5}, {6}'.format(self.id, self.parent, self.brother, self.child, self.depth, self.height, self.type))

def SetNode(I_Line):
	L = list(map(int, I_Line.split()))
	num = L[0]
	left = L[1]
	right = L[2]
	node = Node(num, left, right)
	T[num] = node
	if left != -1:
		T[-1] -= left
	if right != -1:
		T[-1] -= right

def setPBD(i,p,b,d): #??????????????????
    node = T[i]
    node.parent = p
    node.brother = b
    node.depth = d
    if node.parent == -1:
        node.type = "root"
    elif node.child == 0:
        node.type = "leaf"
    else:
        node.type = "internal node"
    if node.left != -1:
        setPBD(node.left, i, node.right, node.depth + 1)
    if node.right != -1:
        setPBD(node.right, i, node.left, node.depth + 1)

def setH(i): #??????????????????
    node = T[i]
    if node.left == -1:
        leftheight = 0
    else:
        leftheight = setH(node.left) + 1
    if node.right == -1:
        rightheight = 0
    else:
        rightheight = setH(node.right) + 1
    node.height = max(leftheight, rightheight)
    return node.height

n = int(input())
T = [None] * n
T.append(int(n * (n-1)/2))
for i in range(n):
    x = input()
    SetNode(x)

root = T[-1]
setPBD(root, -1, -1, 0)
setH(root)
T.pop()
for i in T:
    i.show_info()

Submission status: WA: Presentation Error

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