在写这道题的时候犯了一个错误,迷瞪了半天。这里要提醒一下大家。
在题目中有代码如下:
z->key = k;
z->left=NIL;
z->right=NIL;
这段代码是必要的,不能省略,因为在后面的递归查询的时候,递归的终止条件是
u==NIL
这里给大家分享一个小知识,也是我在做题过程中发现得。
全局指针变量在未赋值前,地址默认为都0。
局部指针变量在未赋值前,地址是任意给定的。
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdlib>
using namespace std;
int it=0;
struct node{
int key;
node *parent, *left, *right;
};
bool fs=false;
node *root, *NIL;
void insert(int k){
node *z=(node*)malloc(sizeof(node));
node *x;
node *y;
z->key = k;
z->left=NIL;
z->right=NIL;
if(fs==false){
root = z;
fs = true;
}else{
x = root;
while(x!=NIL){
y = x;
if(z->key< x->key){
x=x->left;
}else{
x=x->right;
}
}
if(y->key<z->key){
y->right=z;
z->parent=y;
}else{
y->left=z;
z->parent=y;
}
}
}
void print(node *u){
if(u==NIL) return;
cout<<u->key<<" ";
print(u->left);
print(u->right);
}
void opt(node *u){
if(u==NIL) return;
opt(u->left);
cout<<u->key<<" ";
opt(u->right);
}
int main(){
int n, num;
string str;
cin>>n;
for(int i=0; i<n; i++){
cin>>str;
if(str=="insert"){
cin>>num;
insert(num);
}else if(str=="input"){
print(root);
opt(root);
}
}
}