正常来讲,这个是学过的,应该不难;
但是,我是小白,看着就很难……
首先,树的结构体是怎么写的?
报错,很正常
都有文章啊
目前长这样,至少不报错了
#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;
}
}