根据先序遍历建树
const int N=2e6+10; struct node {char date;int l,r; }str[N]; string s; //读入先序遍历 int cnt,idx; int build() {if (s[cnt]=='#'){cnt++;return 0;}str[++idx].date=s[cnt++];int now=idx;str[now].l=build();str[now].r=build();return now; }int u=build();//返回根节点
根据先序和中序建树
const int N=2e6+10; struct node {int date;int l,r; }str[N]; int pre[N],mid[N],n;//读入先序顺序和中序顺序 int cnt,idx; int build(int len,int pre[],int mid[]) {if (len<=0) return 0;str[++idx].date=pre[0];int i;for (i=0;i<len;i++){if (mid[i]==pre[0]) break;}int now=idx;str[now].l=build(i,s+1,p);str[now].r=build(len-i-1,s+i+1,p+i+1);return now; }int u=build(n,pre,mid);//返回根节点
根据中序和后序建树
const int N=2e6+10; struct node {int date;int l,r; }str[N]; int mid[N],post[N],n;//读入中序顺序和后序顺序 int cnt,idx; int build(int len,int mid[],int post[]) {if (len<=0) return 0;str[++idx].date=post[len-1];int i;for (int i=0;i<len;i++){if (mid[i]==post[len-1]) break;}int now=idx;str[now].l=build(i,s,p);str[now].r=build(len-i-1,s+i+1,post+i);return now; }int u=build(n,mid,post);//返回根节点
四种遍历
1.先序遍历
void Post(int u) {if (!u) return ;Post(str[u].l);Post(str[u].r);cout<<str[u].date; }
2.中序遍历
void Mid(int u) {if (!u) return ;Mid(str[u].l);cout<<str[u].date;Mid(str[u].r); }
3.后序遍历
void Post(int u) {if (!u) return ;Post(str[u].l);Post(str[u].r);cout<<str[u].date; }
4.层序遍历
void bfs(int u) {queue <int> q;q.push(u);while (q.size()){int t=q.front();q.pop();cout<<str[t].date;if (str[t].l) q.push(str[t].l);if (str[t].r) q.push(str[t].r);} }
树的高度
int deep(int u) {if (!u) return 0;return max(deep(str[u].l),deep(str[u].r))+1; }