例题10.3二叉排序树(华科)
关键字:二叉排序树的插入、二叉排序树输出父节点
#include<iostream>
#include<vector>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x):val(x),left(nullptr),right(nullptr){}
};
TreeNode* insertBST(TreeNode* root, int x, int father) {
if (root == nullptr) {
root = new TreeNode(x);
cout << father << endl;
}
else if (x < root->val) {
root->left = insertBST(root->left, x, root->val);
}
else if (x > root->val) {
root->right = insertBST(root->right, x, root->val);
}
return root;
}
int main() {
int n;
while (cin >> n) {
TreeNode* root = nullptr;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
root = insertBST(root, x, -1);
}
cout << endl;
}
return 0;
}