考察DFS和二叉树的基本知识
非常老实的写法:
#include <iostream>
#include <string>
using namespace std;
typedef struct Node{
char c;
struct Node*l;
struct Node*r;
}Node;
// 建树
void getTree(Node* &T){
char x;
scanf("%c",&x);
if(x=='#'){
T=NULL;
return;
}else{
T=new Node();
T->c=x;
getTree(T->l);
getTree(T->r);
}
}
// 深度优先遍历
void DFS(Node* &T){
if(T==NULL)return ;
DFS(T->l);
cout<<T->c<<' ';
DFS(T->r);
}
int main(){
Node*T;
getTree(T);
DFS(T);
return 0;
}
边建树边遍历:
两点优化:
- 因为我们在后续不会使用到这棵树,所以其实没必要用结构体指针把整棵树存下来
- 鉴于先序建树的顺序是“根左右”,所以在建立完左子树的时候,根节点已有,此时在建立右子树之前可以直接输出根节点,这样其实相当于“左根右”的中序遍历
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int k;
string str;
void dfs()
{
if (str[k] == '#')
{
k ++ ;
return;
}
//用r来记录当前正在建立结点的值,省去结构体指针存储
char r = str[k ++ ]; // 根节点
dfs(); // 左子树
//建立右子树之前先行输出根节点,达到中序遍历的效果
cout << r << ' ';
dfs(); // 右子树
}
int main()
{
cin >> str;
dfs();
return 0;
}