https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef?tpId=40&tPage=1&rp=1&ru=%2Fta%2Fkaoyan&qru=%2Fta%2Fkaoyan%2Fquestion-ranking&difficulty=&judgeStatus=&tags=583&title=&sourceUrl=&gioEnter=menu
先序序列(含有空结点)构建二叉树
我感觉只能 先序(含空结点)建树
后序(含空结点)和 前序(含空结点)都不能建树
#include <iostream>
#include <cstring>
#include <algorithm>
#include <string>
using namespace std;
typedef class node {
public:
char val;
node* left;
node* right;
node(char c): val(c) {}
}* Node;
string s;
int t = 0;
Node f() {
char c = s[t];
t++;
if (c == '#') return nullptr;
Node no = new node(c);
no->left = f();
no->right = f();
return no;
}
void g(Node r) {
if (!r) {
return;
}
g(r->left);
cout << r->val << ' ';
g(r->right);
}
int main() {
while (cin >> s) {
t = 0;
Node node = f();
g(node);
cout << endl;
}
return 0;
}
#include <iostream>
using namespace std;
class node{
public:
int val;
node* left;
node* right;
node(int x):val(x),left(nullptr),right(nullptr){}
};
// create(root), 此函数用于 创建一棵二叉树,并保存在root中
// 细节: 先序建树, 先根据输入的数建立根节点 1)若输入空结点标记,则这棵树为null,
// 2) 若非空结点标记, 先创建根节点,再递归创建左子树,最后递归创建右子树
void create(node* &root)
{
int x;
cin >> x;
if(x == -1)
{
root = nullptr;
return;
}
else
{
root = new node(x);
create(root->left);
create(root->right);
}
}
void mid(node *r)
{
if(r == nullptr) return;
mid(r->left);
cout << r->val <<' ';
mid(r->right);
}
int main()
{
node* root = nullptr;
create(root);
mid(root);
return 0;
}