思路分析:
这道题主要就是根据后序和中序遍历进行建树。
(1)定义一个树的结构体,结构体成员包含当前节点的左儿子和右儿子。
(2)定义一个建树的函数,由于后序遍历的最后一位是当前数的根节点,所以在中序遍历中找到根节点的位置,然后分为左右子树继续递归。最后返回整个树的根节点。
(3)定义一个层序遍历的函数,传入的是根节点,然后根据队列的方式每次都是先放左儿子再放右儿子。
代码实现:
#includeusing namespace std; struct node { int l; int r; }tree[10010]; int zhong[10010],hou[10010]; queue q; int n; int buildtree(int left,int right,int begin,int end) { if(left>right||begin>end) return -1; int root=hou[right]; int p; for(int i=begin;i<=end;i++) if(zhong[i]==root) { p=i; break; } int sx=p-begin; int sy=end-p; tree[root].l=buildtree(left,left+sx-1,begin,begin+sx-1); tree[root].r=buildtree(right-sy,right-1,end-sy+1,end); return root; } void ceng(int root) { int num; q.push(root); while(!q.empty()) { num=q.front(); q.pop(); if(tree[num].l!=-1) { q.push(tree[num].l); } if(tree[num].r!=-1) { q.push(tree[num].r); } if(num==root) cout< >n; for(int i=0;i >hou[i]; for(int i=0;i >zhong[i]; struct node k; int root; root=buildtree(0,n-1,0,n-1); ceng(root); return 0; }



