AcWing 3540. 构造二叉搜索树模板
原题链接
简单
作者:
jokerlove
,
2022-07-06 16:20:40
,
所有人可见
,
阅读 240
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void buildTree(TreeNode*& root, int m) // 注意&
{
if (!root)
root = new TreeNode(m);
else if (m < root->val)
buildTree(root->left, m); // 向下dfs建树
else if (root->val < m)
buildTree(root->right, m); // 先左先右没影响
}
void pre(TreeNode* root)
{
if (!root)
return;
cout << root->val << ' ';
pre(root->left);
pre(root->right);
}
void in(TreeNode* root)
{
if (!root)
return;
in(root->left);
cout << root->val << ' ';
in(root->right);
}
void post(TreeNode* root)
{
if (!root)
return;
post(root->left);
post(root->right);
cout << root->val << ' ';
}
int main()
{
int n;
cin >> n;
TreeNode* root = NULL;
for (int i = 0; i < n; i++)
{
int m;
cin >> m;
buildTree(root, m);
}
pre(root); cout << endl;
in(root); cout << endl;
post(root);
return 0;
}
什么年代了,还在做传统OJ
义!务!