#include <bits/stdc++.h>
using namespace std;
typedef struct TreeNode {
int data;
struct TreeNode *left, *right;
};
void insertBST(TreeNode* &root,int data,TreeNode* preNode) {
// cout<<"进入insertBST"<<endl;
// cout<<"root="<<root<<endl;
if(root == NULL) {
// cout<<"111"<<endl;
root = (TreeNode*)malloc(sizeof(TreeNode));
root->data = data;
root->left = NULL;
root->right=NULL;
// cout<<"data="<<data<<endl;
if(preNode == NULL) {
cout<<"-1"<<endl;
} else {
cout<<preNode->data<<endl;
}
} else if(root->data < data) {
// cout<<"222"<<endl;
insertBST(root->right,data,root);
} else {
// cout<<"333"<<endl;
insertBST(root->left,data,root);
}
}
int main() {
int n = 0;
cin>>n;
TreeNode *root = NULL;
for(int i = 0 ; i < n; i++) {
int input = 0;
cin>>input;
insertBST(root,input,NULL);
}
return 0;
}
1、root传 空指针的话一定要初始化为NULL

京公网安备 11010502036488号