根据先序遍历递归构建二叉树
代码:
#include<iostream>
#include<cstring>
using namespace std;
char c[105];
int cnt,n;
struct node{
char v;
node* l,*r;
};
node* dfs(){
if(++cnt>n||c[cnt]=='#') return nullptr;
node* t=new node;
t->v=c[cnt];
t->l=dfs();
t->r=dfs();
return t;
}
void pri(node* root){
if(root==nullptr) return;
pri(root->l);
printf("%c ",root->v);
pri(root->r);
}
int main(){
while(~scanf("%s",c+1)){
cnt=0;
n=strlen(c+1);
node* root=dfs();
pri(root);
}
return 0;
}