【发布时间】:2016-03-04 16:06:03
【问题描述】:
我已经实现了二叉搜索树。我的代码很简单。
struct Tree{
Tree* left;
Tree* right;
int value;
};
这里我声明了基本结构。
Tree* makenode(int val){
Tree* tmp= new Tree;
tmp->left=tmp->right=NULL;
tmp->value=val;
return tmp;
}
创建另一个结构类型 Tree 的函数。
void setLeft(Tree* x,int val){
x->left=makenode(val);
}
void setRight(Tree* x,int val){
x->right=makenode(val);
}
void insertt(Tree *x,int val){
while(1){
if(val < x->value){
if(x->left!=NULL){
x=x->left;
}else{
setLeft(x,val);
break;
}
}else{
if(x->right!=NULL){
x=x->right;
}else{
setRight(x,val);
break;
}
}
}
}
循环遍历树并在正确的位置插入值 = 在添加树的同时对树进行排序。
困扰我的是这个小功能
void travel(Tree *x){
if(x->left!=NULL){
travel(x->left);
}
Tree *b;
b=x->right;
if(x->value == b->value){
cout << "Duplicate is " << x->value << endl;
return ;
}
cout << "Value is " << x->value << endl;
if(x->right!=NULL){
travel(x->right);
}
}
如果我省略,它会很好地打印值
Tree *b;
b=x->right;
if(x->value == b->value){
cout << "Duplicate is " << x->value << endl;
return ;
}
我希望它在打印当前值时检查 enxt 值,它们都是相同的 = 我们有重复。但它总是使我的程序崩溃。这是什么原因造成的?排序有效,唯一可能出现的问题是递归行为,但我不知道是什么
我试着把它改造成
void travel(Tree *x, vector<int> &y){
vector<int>::iterator it;
if(x->left!=NULL){
if( x->value == x -> left -> value){
it=find( y.begin(), y.end(), x->value );
if(it==y.end()){
y.push_back(x->value);
}
}
travel(x->left, y);
}
cout << "Value is " << x->value << endl;
if(x->right!=NULL){
if( x->value == x -> right -> value){
it=find( y.begin(), y.end(), x->value );
if(it==y.end()){
y.push_back(x->value);
}
}
travel(x->right,y);
}
}
但是有了这个主函数
int main()
{
vector<int> dups;
Tree * node = makenode(55);
insertt(node,99);
insertt(node,5);
insertt(node,99);
insertt(node,100);
insertt(node,13);
insertt(node,99);
insertt(node,55);
travel(node,dups);
printDup(dups);
return 0;
}
and printDup
使用命名空间标准;
void printDup( vector<int> &y){
cout << "Duplicates are: ";
for( int i = 0; i < y.size(); i++){
cout << y[i] << " ";
}
}
它只打印 99 ,为什么其他值没有被推入向量?另外,我怎样才能使旅行功能变得更优雅?
【问题讨论】:
-
您是否希望您的 BST 允许重复?
-
我想允许重复,然后打印重复
-
既然 rabbid 很好地回答了您的问题,我不会添加任何内容,而且由于您是初学者,您自己实现树真是太好了。一旦掌握了基础知识,请查看标准库,因为它非常强大(在这种特定情况下,
std::map或std::multimap可以大大简化和改进您的代码)。例如,你的整个可以很容易地替换为this。
标签: c++ tree binary-search-tree