Untitled
unknown
plain_text
a year ago
1.9 kB
20
Indexable
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
// TreeNode structure
struct TreeNode {
int val;
vector<TreeNode*> children;
TreeNode(int x) : val(x) {}
};
// Function to build the tree from parent-child relationships
TreeNode* buildTree(const vector<int>& nodeValues, const vector<pair<int, int>>& relationships) {
int n = nodeValues.size();
vector<TreeNode*> nodes(n);
// Create all nodes
for (int i = 0; i < n; ++i) {
nodes[i] = new TreeNode(nodeValues[i]);
}
// Create tree structure
for (const auto& rel : relationships) {
int parentIdx = rel.first;
int childIdx = rel.second;
nodes[parentIdx]->children.push_back(nodes[childIdx]);
}
// Return the root (node 0 is assumed to be the root)
return nodes[0];
}
// Postorder traversal function
void postorderTraversal(TreeNode* root, vector<int>& result) {
if (root) {
for (TreeNode* child : root->children) {
postorderTraversal(child, result);
}
result.push_back(root->val);
}
}
int main() {
int n;
cin >> n;
vector<int> nodeValues(n);
for (int i = 0; i < n; ++i) {
cin >> nodeValues[i];
}
int m;
cin >> m;
vector<pair<int, int>> relationships(m);
for (int i = 0; i < m; ++i) {
int parent, child;
cin >> parent >> child;
relationships[i] = {parent, child};
}
// Build the tree
TreeNode* root = buildTree(nodeValues, relationships);
// Perform postorder traversal
vector<int> postorder;
postorderTraversal(root, postorder);
// Output the postorder traversal
for (size_t i = 0; i < postorder.size(); ++i) {
if (i > 0) cout << " ";
cout << postorder[i];
}
cout << endl;
return 0;
}
Editor is loading...
Leave a Comment