二叉树最大深度

在线刷题 (educoder.net)

正常来讲,这个是学过的,应该不难;

但是,我是小白,看着就很难……

首先,树的结构体是怎么写的?

报错,很正常

 都有文章啊

目前长这样,至少不报错了

#include<iostream>
using namespace std;
#include<string>

typedef struct BitNode{
	char data;
	BitNode* lchild,*rchild;
}BitNode,*BiTree;

BiTree CreateBiTree(string input,int& pos){
	//递归返回条件 
	if(input[pos]=='#'){
		return NULL;
	}
	//先序
	BiTree root=new BitNode;
	root->data=input[pos];
	++pos;
	root->lchild=CreateBiTree(input,pos);
	++pos;
	root->rchild=CreateBiTree(input,pos); 
}

void output(BiTree root){
	if(root==NULL){
		cout<<"#";
		return;
	}
	cout<<root->data;
	output(root->lchild);
	output(root->rchild);
}

int main(){
	string input;
	cin>>input;
	int pos=0;
	BiTree root=CreateBiTree(input,pos);
	output(root);
	return 0;
}

 莫得输出,可能是少了个return?

正常了

后面的,怎么写啊?

这俩有什么区别么?

 是这个关系?

引用自:(82条消息) 二叉树遍历(前序、中序、后序、层次遍历、深度优先、广度优先)_Yadoer的博客-CSDN博客_二叉树遍历

 宽搜,是不是只能借助队列来实现,不能递归?

是不是只有深搜有递归非递归之分?

是的

代码: 

#include<iostream>
using namespace std;
#include<string>

int currentDepth=0; 
int maxDepth=0;

typedef struct BitNode{
	char data;
	BitNode* lchild,*rchild;
}BitNode,*BiTree;

BiTree CreateBiTree(string input,int& pos){
	//递归返回条件 
	if(input[pos]=='#'){
		return NULL;
	}
	//先序
	BiTree root=new BitNode;
	root->data=input[pos];
	++pos;
	root->lchild=CreateBiTree(input,pos);
	++pos;
	root->rchild=CreateBiTree(input,pos); 
	
	return root;
}
//先序遍历 
void output(BiTree root){
	if(root==NULL){
		cout<<"#";
		return;
	}
	cout<<root->data;
	output(root->lchild);
	output(root->rchild);
}
//深搜 
void DFS(BiTree root){
	if(root==NULL){
		return;
	}
	currentDepth++;
	if(currentDepth>maxDepth){
		maxDepth=currentDepth;
	}
	DFS(root->lchild);
	DFS(root->rchild);
	currentDepth--;
	
}

int main(){
	string input;
	cin>>input;
	int pos=0;
	BiTree root=CreateBiTree(input,pos);
	//测试树对不对 
//	output(root);
//	cout<<endl;
	DFS(root);
	cout<<maxDepth<<endl;
	return 0;
}

结果上是过了……

 然后发现,书上是有深度计算的

这个才是正宗的递归,你那写的,都是些什么垃圾……

小白嘛,很正常……但是一直都是小白,就不正常了……

//深搜 
void DFS(BiTree root){
	if(root==NULL){
		return;
	}
	currentDepth++;
	if(currentDepth>maxDepth){
		maxDepth=currentDepth;
	}
	DFS(root->lchild);
	DFS(root->rchild);
	currentDepth--;
	
}

int getDepth(BiTree root){
	if(root==NULL){
		return 0;
	}
	int leftDepth=getDepth(root->lchild);
	int rightDepth=getDepth(root->rchild);
	if(leftDepth>rightDepth){
		return leftDepth+1;
	}else{
		return rightDepth+1;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值