题解 | 二叉排序树
二叉排序树
https://www.nowcoder.com/practice/30a0153649304645935c949df7599602
#include <iostream> using namespace std; struct tree { int data; tree* parent; tree* left=NULL; tree* right=NULL; }; void build(tree*& root, tree* parent, int x) { if (root == NULL) { root = new tree; root->data = x; root->parent = parent; if (root->parent == NULL)cout << -1 << endl; else cout << root->parent->data << endl; return; } if (x < root->data) build(root->left, root, x); else build(root->right, root, x); } int main() { int n; while (cin >> n) { // 注意 while 处理多个 case tree* root=NULL; for (int i = 0; i < n; i++) { int x; cin >> x; build(root, NULL, x); } } } // 64 位输出请用 printf("%lld")