AcWing 1589. 构建二叉搜索树(清晰易懂版)
原题链接
中等
作者:
cppgod
,
2021-04-27 11:32:46
,
所有人可见
,
阅读 437
- 首先根据给定的关系构建树的基本形状;
- 将排序好的数组值,中序遍历去填好每个节点的值;
- 最后层序遍历即可。
C++ 代码
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 102;
int val[MAXN];
int n;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() : val(-1), left(nullptr), right(nullptr) {}
TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}
TreeNode(int v, TreeNode* l, TreeNode* r) :
val(v), left(l), right(r) {}
};
int main()
{
cin >> n;
vector<pair<int, int>> relation(n);
for (int i = 0; i < n; ++i)
cin >> relation[i].first >> relation[i].second;
for (int i = 0; i < n; ++i)
cin >> val[i];
sort(val, val + n);
unordered_map<int, TreeNode*> m;
for (int i = 0; i < n; ++i) {
TreeNode* parent;
if (m.count(i))
parent = m[i];
else {
parent = new TreeNode();
m.emplace(i, parent);
}
int l = relation[i].first;
int r = relation[i].second;
if (l != -1) {
if (m.count(l)) {
parent->left = m[l];
} else {
parent->left = new TreeNode();
m.emplace(l, parent->left);
}
}
if (r != -1) {
if (m.count(r)) {
parent->right = m[r];
} else {
parent->right = new TreeNode();
m.emplace(r, parent->right);
}
}
}
stack<TreeNode*> s;
TreeNode *root = m[0];
int idx = 0;
while (root || !s.empty()) {
while (root) {
s.push(root);
root = root->left;
}
root = s.top(); s.pop();
root->val = val[idx++];
root = root->right;
}
queue<TreeNode*> q{{m[0]}};
while (!q.empty()) {
auto node = q.front();
q.pop();
cout << node->val << " ";
if (node->left)
q.push(node->left);
if (node->right)
q.push(node->right);
}
return 0;
}