思路:用dfs的方法求,节点的儿子若就是该节点的拓展方向。然后所有的叶子节点中,深度最大的叶子节点的深度就代表了这棵
二叉树的深度。
#include<stdio.h>
#include<iostream>
#include<stdlib.h>
using namespace std;
struct node
{
char v;
int num;
int depth;
struct node*ls,*rs;
};
int ans=-0x3f3f3f3f;
char mb;
struct node*head;
struct node*build()//
{
char ch;
cin>>ch;
if(ch=='#') return NULL;
struct node*p=(struct node*)malloc(sizeof(struct node));
p->v=ch;
p->ls=build();
p->rs=build();
return p;
};
void getdepth(struct node*p,int depth)
{
if(!p) return ;
p->depth=depth;
if(p->ls==NULL&&p->rs==NULL) ans=max(ans,p->depth);
getdepth(p->ls,depth+1);
getdepth(p->rs,depth+1);
}
void middle(struct node*p)
{
if(!p) return ;
middle(p->ls);
cout<<"/节点的值:"<<p->v<<" 深度:"<<p->depth<<endl;
middle(p->rs);
}
int main()
{
head=build();
getdepth(head,1);
middle(head);
cout<<"/树的深度:"<<ans<<endl;
return 0;
}