首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >二进制搜索树(搜索功能)

二进制搜索树(搜索功能)
EN

Stack Overflow用户
提问于 2013-02-24 04:32:48
回答 1查看 165关注 0票数 0
代码语言:javascript
运行
复制
template <class T>
struct TreeNode{
  string value;
  T key;
  TreeNode<T> *Parent;
  TreeNode<T> *LeftChild;
  TreeNode<T> *RightChild;
  TreeNode (T k,string Val)
  {
           this->value=Val;
           this->key=k;
           this->Parent=NULL;
           this->LeftChild=NULL;
           this->RightChild=NULL;
  }
};

template <class T>
class BinaryTree{
  private:
       TreeNode<T> *Root;        
  public:  
       BinaryTree();
       ~BinaryTree();
       void insertNode(T Key,string Val);
       void deleteNode(T Key);
       string searchNode(T Key);
       void UpdateKey(T newkey,T oldkey);
       int Height(TreeNode<T> *node);
       int height();
};




template <class T>
string BinaryTree<T>::searchNode(T Key)
{        
TreeNode<T> *temp=Root;
while (temp!=NULL)
{
      if (temp->key==Key)
      {
          cout<<temp->key<<endl;                             
          return temp->value;
      }
      if (temp->key>Key)
      {
          temp=temp->LeftChild;
      }
      else if (temp->key<Key)
      {
           temp=temp->RightChild;
      }                  
}     
return "\0";
}

我在做一个二叉搜索树。但是当我运行我的搜索函数时,它总是返回空值,即使该值存在于树中。要么是我的构造函数不正确,要么是我的搜索函数有问题。我似乎找不出问题所在。下面是构造函数:

代码语言:javascript
运行
复制
template <class T>
BinaryTree<T>::BinaryTree()
{
Root=NULL;                       
ifstream fin;
fin.open("names.txt");
string buffer;
T buff;
while (!fin.eof())
{
      getline(fin,buffer,'~');
      fin>>buff;

      TreeNode<T> *temp,*temp1;
      temp=Root;
      temp1=temp;
      while (temp!=NULL)
      {
          temp1=temp;  
          TreeNode<T> *Right=temp->RightChild;
          TreeNode<T> *Left=temp->LeftChild;
          if (temp->key>buff)
          {
              temp=temp->LeftChild;
          }
          else if (temp->key<buff)
          {
              temp=temp->RightChild;
          }
          else
          {
              temp=temp->LeftChild;
          }
      }
      if (temp!=Root)
      temp->Parent=temp1;
      temp=new TreeNode<T>(buff,buffer);
}
fin.close();
}
EN

回答 1

Stack Overflow用户

发布于 2013-02-24 04:46:25

首先,这不属于构造函数。这应该在readFile()方法或某个operator>>()中。

现在来看看你的read函数

不要检查

代码语言:javascript
运行
复制
while (!fin.eof())

检查一下

代码语言:javascript
运行
复制
while (std::getline(fin, buffer, '~'))

而不是。

最后,您从不向树中添加任何内容,只向一些temp变量添加内容。这可能是搜索功能失败的原因。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15045333

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档