用递归的方法求一个二叉树的深度。
1. 空树的深度为0.
2. 非空树的深度,为其左右子树中深度较大的子树的深度+1.
代码实现:
typedef struct node{
item_t item;
struct node *left;
struct node *right;
} node_t;
typedef node_t * BinaryTree;
int depth(BinaryTree root) {
int ldepth, rdepth;
if( root) {
ldepth = depth(root->left);
rdepth = depth(root->right);
return ( ldepth > rdepth ? ldepth : rdepth) + 1;
}
return 0;
}
2. 非递归的方法: 可以用层次遍历,这棵树,记录层次总数,就是树的深度。使用的数据结构(队列)。