常见的二叉树遍历的题目,根据后序遍历和中序遍历求层次遍历。
通过后序遍历和中序遍历建立起一棵二叉树,然后层序遍历一下,主要难点在于树的建立,通过中序遍历和后序遍历的特点递归求解,详细内容见代码
#include <iostream> #include <queue> using namespace std; struct TreeNode{ int val; TreeNode* left; TreeNode* right; }; int post[30]; int in[30]; int n; TreeNode* root; void BuildTree(int l1, int r1, int l2, int r2, TreeNode*& root) { root = new TreeNode(); int i; for ( i = l2; i <= r2; i++) { if (in[i] == post[r1]) break; } root->val = post[r1]; if (i == l2) root->left = NULL; else BuildTree(l1, l1 + i - l2 - 1, l2, i - 1,root->left); //边界条件 if (i == r2) root->right = NULL; else BuildTree(l1+i-l2, r1 - 1, i + 1, r2, root->right); //边界条件 } int flag = 0; void levelorder(TreeNode* T){ queue<TreeNode*> q; q.push(T); while (!q.empty()){ TreeNode* t = q.front(); q.pop(); if (t->left) q.push(t->left); if (t->right) q.push(t->right); if (flag == 0){ cout << t->val; flag = 1; } else{ cout << " " <<t->val; } } cout << endl; } void prevTree(TreeNode* root) { if (root == NULL) return; cout << root->val << " "; prevTree(root->left); prevTree(root->right); } int main(void){ cin >> n; for (size_t i = 0; i < n; i++) cin >> post[i]; for (size_t i = 0; i < n; i++) cin >> in[i]; BuildTree(0, n - 1, 0, n - 1, root); levelorder(root); }