每日一题 7.28
给定一个二叉树,找出其最大深度。二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
思路:
- 建立二叉树结构
- 建立二叉树,创造结点
- 递归求解二叉树深度
- 释放结点
代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct tree //结构体的名字为tree
{
char ch;
struct tree *lchild;
struct tree *rchild;
}tree;
tree *CreateTree()
{
tree *bt;
char str;
scanf("%c",&str);
if(str=='0')
return NULL;
else
{
bt=(tree *)malloc(sizeof(tree));
bt->ch=str;
bt->lchild=CreateTree();
bt->rchild=CreateTree();
return bt;
}
}
int DeepOrder(tree *bt)
{
int ld=0,rd=0;
if(bt)
{
ld=DeepOrder(bt->lchild)+1;
rd=DeepOrder(bt->rchild)+1;
}
return ld>=rd?ld:rd;
}
void DestroyTree(tree *bt)
{
if(bt)
{
DestroyTree(bt->lchild);
DestroyTree(bt->rchild);
free(bt);
}
}
int main(void)
{
tree *bt;
printf("请以先序输入二叉树(0表示该结点的子结点为空):\n");
bt=CreateTree();
printf("bt为: %s",bt);
int deep=DeepOrder(bt);
printf("\n二叉树的深度为: %d\n",deep);
printf("\n");
DestroyTree(bt);
return 0;
}
温馨提示: 遵纪守法, 友善评论!