[2] 后序遍历:后序遍历是深度优先遍历二叉树的一种方法,它的递归定义是:先后序遍历左子树,再后序遍历右子树,最后访问根。
方法一:建树
#include<iostream> #include<cstdio> #include<cstring> using namespace std; char s[2000],r[2800]; void build_FBI(int k,int left,int right) { if(left==right) { r[k]=s[right]; return; } int mid=(left+right)/2; build_FBI(2*k,left,mid); build_FBI(2*k+1,mid+1,right); if(r[2*k]=='0'&&r[2*k+1]=='0')r[k]='0'; else if(r[2*k]=='1'&&r[2*k+1]=='1')r[k]='1'; else r[k]='2'; } void dfs(int v){ if(r[2*v]) dfs(2*v); if(r[2*v+1]) dfs(2*v+1); if(r[v]=='0') printf("B"); else if(r[v]=='1') printf("I"); else printf("F"); } int main() { int n; scanf("%d",&n); scanf("%s",s+1); build_FBI(1,1,strlen(s+1)); dfs(1); }
方法二:直接递归
#include <iostream> #include <cstdio> #include <string> using namespace std; string str; void fbi(int left,int right) { if(left>right) return ; int mid=(left+right)/2,B=0,I=0; if(left!=right) { fbi(left,mid); fbi(mid+1,right); } while(left<=right) if(str[left++]=='0') B++; else I++; if(B!=0&&I!=0) printf("F"); else if(I!=0&&B==0) printf("I"); else printf("B"); } int main() { int n; scanf("%d",&n); cin>>str;getchar(); fbi(0,str.size()-1); return 0; }
原文地址:http://blog.csdn.net/u014492609/article/details/44227843