二叉树
二叉树就是每个节点至多有两个子节点的树。
关于树结构,我们在上一篇《数据结构与算法之有根树的表达》中已经讲过了。所以这里就简单讲讲二叉树怎么表达。
二叉树的表达相对比较容易,只要定义好每个节点的父节点、左子节点、右子节点即可。这可以很方便地用结构体来实现。
计算二叉树的高
怎么计算二叉树的高呢?根据树高的定义,我们知道,每个节点的高是max(左子节点的高+1,右子节点的高+1)。只需要递归地进行计算,就能算出节点的高。
这样的算法需要把每个节点都遍历一次,因此复杂度为O(N)
题目
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 t

最低0.47元/天 解锁文章
2581

被折叠的 条评论
为什么被折叠?



