洛谷官方好像没有完整的题解
所以放一下我的AC代码.
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int n;
class node
{
public:
int key;//当前数据记录的数值
node* left;//左节点记录的数值
node* right;//右节点记录的数值
node(int data) : key(data),left(nullptr),right(nullptr){}
};
using bnode = node*;
vector<bnode> Tree(N,nullptr);
void buildTree(int n,vector<pair<int,int>> tree_node)
{
for(int i = 1; i <= n ; i++){
Tree[i] = new node(i);
}
for(int i = 1 ; i <= n ; i++)
{
int l = tree_node[i-1].first;
int r = tree_node[i-1].second;
if(l != 0)Tree[i]->left = Tree[l];
if(r != 0) Tree[i]->right = Tree[r];
}
}
void preIntraversal(node* root)
{
if(root == nullptr) return;
cout << root->key << " ";
preIntraversal(root->left);
preIntraversal(root->right);
}
void inordTraversal(bnode root)
{
if(root == nullptr) return;
inordTraversal(root->left);
cout << root->key << " ";
inordTraversal(root->right);
}
void posTraversal(bnode root)
{
if(root == nullptr) return;
posTraversal(root->left);
posTraversal(root->right);
cout << root->key << " ";
}
int main()
{
cin >> n;
vector<pair<int,int>> tree_node;
int a,b;
for(int i = 1 ; i <= n ; i++)
{
cin >> a >> b;
tree_node.push_back({a,b});
}
buildTree(n,tree_node);
bnode root = Tree[1];
preIntraversal(root);cout << endl;
inordTraversal(root);cout << endl;
posTraversal(root);
return 0;
}