提示:
只给出先序遍历,就能还原出一颗树?莫要逗我!
诶,还真可以,为什么平时老师说必须要先序+中序才能还原一颗树(当然其他序也可以,仅做举例),是因为如果只给出先序遍历,不知道哪里应该在什么时候设置为空子树,也就是不知道该在什么地方终止往下递归。
但是如果用#表示不能继续往下递归了,那不就是说明了如果我按照题目要求去先序遍历,如果要停止了就会告诉我停止,这样的二叉树不就是唯一的嘛?
思路:
模拟先序遍历过程,还原一颗树即可。所以依旧是模板题,在做了几道类似的题目后发现:
- 如果只给出一种遍历让你还原一棵树,十有八九就是模拟递归过程。
- 而如果给出两种遍历让你还原一棵树,也是模板题,在前几年天梯赛考过,所以建议去学习一下。
参考代码:
#include<iostream>
#include<vector>
using namespace std;
struct Node {
char val;
Node* lhs;
Node* rhs;
};
char endChar;
Node* dfs(Node* root) {
char ch; cin>>ch;
if(ch == '#') return NULL; // 如果是空节点,停止往下递归
root = new Node();
root->val = ch;
root->lhs = dfs(root->lhs);
root->rhs = dfs(root->rhs);
return root;
}
void find(vector<char> path, Node* node) {
if(node!=NULL && node->val == endChar) {
path.push_back(endChar);
for(int i=0;i<path.size();++i) {
cout<<path[i]<<" ";
}
return;
}
if(node!=NULL) {
path.push_back(node->val);
find(path, node->lhs);
find(path, node->rhs);
}
}
int main() {
Node* root;
root = dfs(root);
cin>>endChar;
find(vector<char>(), root);
return 0;
}