【华为练习题】二叉树遍历

时间:2023-02-13 21:35:07

【华为练习题】二叉树遍历

题目

二叉树遍历

描述: 二叉树的前序、中序、后序遍历的定义:
前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树;
中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树;
后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。
给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。

输入:
两个字符串,其长度n均小于等于26。
第一行为前序遍历,第二行为中序遍历。
二叉树中的结点名称以大写字母表示:A,B,C….最多26个结点。

输出:
输入样例可能有多组,对于每组测试样例,
输出一行,为后序遍历的字符串。

样例输入:
ABC
BAC
FDXEAG
XDEFAG

样例输出:
BCA
XEDGAF

分析

用递归的方式生成二叉树,再对二叉树进行后续遍历

解答

#include <iostream>
#include <string>
using namespace std;

struct BTreeNode
{
char value;
BTreeNode *left;
BTreeNode *right;
};

void findBack(const string &front, const string &mid, BTreeNode *root){
char value = front[0];
int index = mid.find(value), length = (int)front.size();
if (index < 0) return;
if (index > 0)
{
char leftValue = front[1];
BTreeNode *left = new BTreeNode;
root->left = left;
left->value = leftValue;
left->left = NULL;
left->right = NULL;
findBack(string(front.begin()+1, front.begin()+index+1), string(mid.begin(), mid.begin()+index),left);
}
if (index < length - 1)
{
char rightValue = mid[index + 1];
BTreeNode *right = new BTreeNode;
root->right = right;
right->value = rightValue;
right->left = NULL;
right->right = NULL;
findBack(string(front.begin()+index+1, front.end()), string(mid.begin()+index+1,mid.end()),right);
}
}

void backVisit(BTreeNode *root){
if (root->left) backVisit(root->left);
if (root->right) backVisit(root->right);
cout << root->value;
delete root;
}

int main(){
string front, mid;
while (cin >> front >> mid)
{
BTreeNode *root = new BTreeNode;
root->value = front[0];
findBack(front, mid, root);
backVisit(root);
cout << endl;
}
return 0;
}