题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805485033603072
这道题算是入门题了吧,后序和中序建立二叉树,再用BFS层序遍历,记录一下自己的几个问题
- 建立二叉树的时候一定要写出左子树的个数变量,一开始用自己的写法发现程序运行不正常,一定要定义numLeft = i - inL,然后看一下root的左右子树的建立范围
- BFS的时候不要忘了在获得队首元素后将它pop
代码
#include<algorithm>#include<iostream>#include<queue>using namespace std;vector<int> post, in;struct node{int data;node* leftchild;node* rightchild;};node* create(int postL, int postR, int inL, int inR){if(postL > postR) return NULL;node* root = new node;root->data = post[postR];int i;for(i = inL; i <= inR; i++){if(in[i] == post[postR]) break;}int numLeft = i - inL;root->leftchild = create(postL, postL + numLeft - 1, inL, i - 1);root->rightchild = create(postL + numLeft, postR - 1, i + 1, inR);return root;}int main(){int n;scanf("%d",&n);post.resize(n), in.resize(n);for(int i = 0; i < n; i++) scanf("%d", &post[i]);for(int i = 0; i < n; i++) scanf("%d", &in[i]);node* root = create(0, n - 1, 0, n - 1);queue<node*> q;q.push(root);while(!q.empty()){node * top = q.front();q.pop();printf("%d", top->data);if(top->leftchild != NULL) q.push(top->leftchild);if(top->rightchild != NULL) q.push(top->rightchild);if(q.size() != 0) printf(" ");}return 0;}
