1. 题意
- 题目描述
根据给定的二叉树结构描述字符串,输出该二叉树按照中序遍历结果字符串。中序遍历顺序为:左子树,根结点,右子树
- 输入
由大小写字母、左右大括号、逗号组成的字符串:字母代表一个节点值,左右括号内包含该节点的子节点。
左右子节点使用逗号分隔,逗号前为空则表示左子节点为空,没有逗号则表示右子节点为空。
二叉树节点数最大不超过 100。
注:输入字符串格式是正确的,无需考虑格式错误的情况
- 输出
输出一个字符串为二叉树中序遍历各节点值的拼接结果
- 样例
2. 题解
题目考察的知识点就是递归加中序遍历,但对于我来说还是觉得有点困难。
最主要是递归建树上。
递归最主要的难点在于,找到重复子问题和边界划分。
重复子问题显然就是建树,根据指定字符串来建树。
边界问题比较难处理,先找到递归转移条件。
先处理碰到的字符,实际上就是树根节点。再处理下一个字符。
遇到{
执行递归,先递归建立左子树,执行完成后看下一个字符是不是,
,如果是就再递归建立右子树。最后检查返回的是否是}
。返回根节点。
建好树之后,再执行个中序遍历完事。
还是看代码比较好
#include <iostream>
#include <string>
using namespace std;
struct node {
node( char c_, node *l_, node *r_):c(c_),l(l_),r(r_) {}
char c;
node *l;
node *r;
};
node *build_tree(const string &s, int &p)
{
node *rt = nullptr;
if ( std::isalpha(s[p]) ) {
rt = new node(s[p], nullptr, nullptr);
p++;
if ( s[p] == '{') {
p++;
rt->l = build_tree(s, p);
if ( s[p] == ',') {
++p;
rt->r = build_tree(s, p);
}
if (s[p] == '}')
p++;
}
}
return rt;
}
void inorder_trav(node *rt, string &ans)
{
if (nullptr == rt)
return;
inorder_trav(rt->l, ans);
ans += rt->c;
inorder_trav(rt->r, ans);
}
int main()
{
string s;
cin >> s;
int p = 0;
auto rt = build_tree(s, p);
string ans;
inorder_trav(rt, ans);
cout << ans << endl;
return 0;
}
// a{b{d},c{,e}}
// dbace
// d{b{a,c},f{e,g}}
// abcdefg