如题,自学了二叉查找树,但码的时候测试发现每一个数最后都会搜到NULL(我的思路是查找数如果在该层分支的左子树则输出left,右子树则输出right,然后继续递归查找,直到找到该数输出this。已经插入树中的结点按照我的想法应该是能够搜出来的。)也就是说明明已经插入树里的结点总是搜不出来,同时也无法调试树的结构。求大佬们帮找找看问题所在谢谢!
下面贴上修改前代码
#include<bits/stdc++.h>
using namespace std;
struct node{
node *rch,*lch;
int num;
node(){
rch = lch = NULL;
}
};
void insert(node *&root,int x){
if (root == NULL){
root = new node;
root -> num = x;
return;
}
if (x < root -> num){
insert(root -> lch,x);
}
else{
insert(root -> rch,x);
}
}
void search(node *root,int x){
if (root == NULL)
{cout << "NULL" << "\n";return;
}
if (x == root -> num){
cout << "this" << "\n";
return;
}
if (x > root -> num){
cout << "right" << " ";
search(root -> lch,x);
}
if (x < root -> num){
cout << "left" << " ";
search(root -> rch,x);
}
}
void midord(node *root){
if (root == NULL){
return;
}
midord(root -> lch);
cout << root -> num << " ";
midord(root -> rch);
}
int n,m;
int main(){
node *root;
cin >> n >> m;
for (int i = 1,x;i <= n;i++){
cin >> x;
insert(root,x);
}
midord(root);
for (int i = 1,q,x; i <= m;i++){
cin >> q;
if (q == 1){
cin >> x;
insert(root,x);
}
if (q == 2){
cin >> x;
search(root,x);
}
}
return 0;
}