题解 | #二叉排序树#
二叉排序树
https://www.nowcoder.com/practice/30a0153649304645935c949df7599602
#include <iostream>
using namespace std;
struct node {
int data;
node* leftChild;
node* rightChild;
node(int a) {
data = a;
leftChild = NULL;
rightChild = NULL;
}
};
int father;
node* insert(int a, node* root, int f) {
if (root == NULL) {
node* newNode = new node(a);
father = f;
return newNode;
}
if (a < root->data) root->leftChild = insert(a, root->leftChild, root->data);
else root->rightChild = insert(a, root->rightChild, root->data);
return root;
}
int main() {
int n;
while (cin >> n) { // 注意 while 处理多个 case
node* root = NULL;
while (n--) {
int temp;
cin >> temp;
root = insert(temp, root, -1);
cout << father << endl;
}
}
}
// 64 位输出请用 printf("%lld")