题目描述:求二叉树的深度,来一道简单一点的,早点睡了。
分析:求二叉树的深度实际上很简单,通过递归就可以实现。DL,DR记录左子树深度和右子树深度,递归遍历二叉树t,如果t->left!=NULL,那就继续遍历t->left,如果t->right!=NULL那就继续遍历t->right;最后return 做一个判断取大值+1,为什么+1?因为加上根节点的层数
typedef struct d{
int data
struct d *left
struct d *right
}tree
tree *buildtree(int *a,int &n)
{
int num=a[n++]
if(num==NULL)
{
return NULL
}
tree *s=(tree *)malloc(sizeof(tree))
s->data=num
s->left=buildtree(a,n)
s->right=buildtree(a,n)
return s
}
int TheTreeDeep(tree *t)
{
int DL=0,DR=0
if(t->left!=NULL)
{
DL=TheTreeDeep(t->left)
}
if(t->right!=NULL)
{
DR=TheTreeDeep(t->right)
}
return (DL>DR?DL:DR)+1
}
int main()
{
int a[]={1,2,4,0,0,5,0,0,3,6,0,0,7,0,0}
int n=0
tree *t=buildtree(a,n)
int ret=TheTreeDeep(t)
printf("\n%d\n",ret)
}