【数据结构与算法】根据前序序列重构二叉树
#include <bits/stdc++.h>
using namespace std;
vector<string> a;
int idx = 0;
struct Node {
string val;
Node* left;
Node* right;
Node(string x):val(x),left(nullptr),right(nullptr){}
};
Node* buildTree() {
if (idx >= a.size()) return nullptr;
if (a[idx]=="#") {
idx++;
return nullptr;
}
Node* node = new Node(a[idx]);
idx++;
node->left = buildTree();
node->right = buildTree();
return node;
}
void pre(Node* root) {
if (root == nullptr) {
return;
}
cout<<root->val<<endl;
pre(root->left);
pre(root->right);
}
int main() {
int n;
string ch;
cin >> n;
for (int i = 0;i < n;i++) {
string b;
cin>>b;
a.push_back(b);
}
Node* root = buildTree();
pre(root);
return 0;
}
1
/ \
2 3
\ /
4 5
版权申明
本文系作者 @xiin 原创发布在To Future$站点。未经许可,禁止转载。
暂无评论数据