算法与数据结构之二叉树

二叉树

二叉树就是每个节点至多有两个子节点的树。

关于树结构,我们在上一篇《数据结构与算法之有根树的表达》中已经讲过了。所以这里就简单讲讲二叉树怎么表达。

二叉树的表达相对比较容易,只要定义好每个节点的父节点、左子节点、右子节点即可。这可以很方便地用结构体来实现。

计算二叉树的高

怎么计算二叉树的高呢?根据树高的定义,我们知道,每个节点的高是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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值