题目描述:
有一棵二叉树,每个节点由一个大写字母标识(最多 26 个节点)。现有两组字母,分别表示后序遍历(左孩子->右孩子->父节点)和中序遍历(左孩子->父节点->右孩子)的结果,请输出层次遍历的结果。
输入描述:
输入为两个字符串,分别是二叉树的后续遍历和中序遍历结果。
输出描述:
输出二叉树的层次遍历结果。
示例:
输入
CBEFDA CBAEDF
输出
ABDCEF
C++源码:
#include <iostream>
#include <queue>
#include <string>
using namespace std;
struct TreeNode {
char val;
TreeNode* left;
TreeNode* right;
TreeNode(char x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* buildTree(const string& postorder, const string& inorder, int inStart, int inEnd, int postStart, int postEnd) {
if (inStart > inEnd) return NULL;
TreeNode* root = new TreeNode(postorder[postEnd]);
int inorderRootIndex = inStart;
for (; inorder[inorderRootIndex] != root->val; ++inorderRootIndex);
int leftTreeSize = inorderRootIndex - inStart;
root->left = buildTree(postorder, inorder, inStart, inorderRootIndex - 1, postStart, postStart + leftTreeSize - 1);
root->right = buildTree(postorder, inorder, inorderRootIndex + 1, inEnd, postStart + leftTreeSize, postEnd - 1);
return root;
}
void bfs(TreeNode* root) {
if (!root) return;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
cout << node->val;
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
int main() {
string postorder, inorder;
cin >> postorder >> inorder;
TreeNode* root = buildTree(postorder, inorder, 0, inorder.size() - 1, 0, postorder.size() - 1);
bfs(root);
cout << endl;
system("pause");
return 0;
}