解题关键:建树的时候用stl或者递归建立就好,不用苦苦的手写栈和队列。重要的是思维。
#include<bits/stdc++.h> using namespace std; typedef long long ll; struct node{ int x; node *l,*r; }tr; int num,tmp=0; node* bfs(){ node *t=new node(); tmp++; scanf("%d",&t->x); queue<node*>que; que.push(t); while(!que.empty()){ node *t1=que.front(); que.pop(); tmp++; if(tmp>num) break; node *t2=new node(); scanf("%d",&t2->x); t1->l=t2; que.push(t2); tmp++; if(tmp>num) break; node *t3=new node(); scanf("%d",&t3->x); t1->r=t3; que.push(t3); } return t; } void bfs2(node *root){ queue<node*>que; que.push(root); while(!que.empty()){ node *ss=que.front(); que.pop(); printf("%d ",ss->x); if(ss->l) que.push(ss->l); if(ss->r) que.push(ss->r); } } int main(){ num=8; node *s=bfs(); bfs2(s); }