我在binay搜索树实现C ++中的问题 [英] my problem in binay search tree implementation C++
本文介绍了我在binay搜索树实现C ++中的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
任何人都可以帮助我。我重写了很多次而且我不知道原因?
#include< iostream>
#include< stdlib.h>
typedef int EType;
typedef struct tnode
{
EType data;
struct tnode * left;
struct tnode * right;
} TNode;
typedef struct tnode * BTREE;
TNode * insertBST(BTREE T,EType x);
TNode * insert_left(BTREE T,EType x);
TNode * insert_right(BTREE T,EType x);
TNode * find(BTREE T,EType x);
int main(){
BTREE a,s; a = s = NULL;
insertBST(a, 4 ); insertBST(a, 3 );
}
TNode * insertBST(BTREE T,EType x){
TNode * comp;
if (T == NULL){
comp = new TNode;
if (comp == NULL) return comp;
else {T-> data = x;
T-> left = T-> right = NULL;
} T = comp;
}
else if (x< T->数据)T->左= insertBST(T->左,X);
else T-> right = insertBST(T-> right,x);
return (T);
}
TNode * find(BTREE T,EType x){
if (T-> data == x || T == NULL) return T;
else if (x< T-> data)返回找到(T->左,x);
else return find(T-> right,x);
}
解决方案
在调试器中单步执行 - 你'我会看到InsertBST
从根本上是有缺陷的...
1.当T为null时你的if / else子句是不正确的范围,我猜你得到null +偏移异常?
2.当T为空时,调用者永远不会使用什么*假设*返回,所以第二次调用将以同样的方式失败
和一个观察,因为爱奶酪不使用typedef故意模糊,如果某事是ptr或对象(BTREE特别在这里)
can any one help me in this. i rewrite it many times and i don't know the reason?
#include<iostream>
#include<stdlib.h>
typedef int EType;
typedef struct tnode
{
EType data;
struct tnode* left;
struct tnode* right;
}TNode;
typedef struct tnode* BTREE;
TNode* insertBST(BTREE T,EType x);
TNode* insert_left(BTREE T,EType x);
TNode* insert_right(BTREE T,EType x);
TNode* find(BTREE T, EType x);
int main(){
BTREE a,s;a=s=NULL;
insertBST(a,4);insertBST(a,3);
}
TNode* insertBST(BTREE T,EType x){
TNode* comp;
if(T==NULL){
comp=new TNode;
if(comp==NULL)return comp;
else{T->data=x;
T->left=T->right=NULL;
}T=comp;
}
else if(x<T->data)T->left=insertBST(T->left,x);
else T->right=insertBST(T->right,x);
return(T);
}
TNode* find(BTREE T, EType x){
if(T->data==x||T==NULL)return T;
else if(x<T->data)return find(T->left,x);
else return find(T->right,x);
}
解决方案
single step it in the debugger - you'll see thatInsertBST
is fundamentally flawed ...
1. when T is null your if/else clause is incorrectly scoped, i'm guessing you get null+offset exceptions?
2. when T is null, the caller never gets to use what is *supposed* to be returned, so the second call will fail the same way
and an observation, for the love of cheese don't use typedefs that deliberately obscure if something is a ptr or an object (BTREE specifically here)
这篇关于我在binay搜索树实现C ++中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文