按位置搜索,二叉树C ++

时间:2017-05-12 13:33:04

标签: c++ binary-tree

我正在努力在二叉树中执行递归函数,我正在尝试创建一个请求位置的函数,然后它返回该位置的值,我花了很多次对代码和大部分时间它只是死了。所以如果有人知道我做错了什么,我会非常感激,非常感谢你。

    struct node
{
    int info;
    struct node *left;
    struct node *right;
}*root;

class BST
{
    public:
        void find(int, node **, node **);
        void insert(node *tree, node *newnode);
        void del(int);
        void case_a(node *,node *);
        void case_b(node *,node *);
        void case_c(node *,node *);
        void preorder(node *);
        void inorder(node *);
        void postorder(node *);
        void display(node *, int);
        void recupera(int pos);
        int countNodes(node *);
        int busquedaPos(node *ptr,int c,int pos);
        BST()
        {
            root = NULL;
        }
};


    int BST::busquedaPos(node *ptr,int c, int pos)
{
    while(c != pos+1){
        busquedaPos(ptr->left,c+1,pos);
        busquedaPos(ptr->right,c+1,pos);
    }
    return ptr->info;
}

void BST::recupera(int pos)
{
    int y = 1;
    if(root == NULL)
    {
        cout<<"\tEmpty tree."<<endl;
    }
    else if (pos==1){
        cout<<"Your position is the root, so the value is: "<<root->info<<". "<<endl;
    }
    else if(pos>1 && pos <= (countNodes(root)))
    {
        bool found = false;
        while( y != pos && found != true){
                cout<<"ok"<<endl;
            int plz = busquedaPos(root,y,pos);
        cout<<"ok2"<<endl;
            cout<<"Your value is: "<< plz <<endl;
                found = true;
            }
    }
    else if(pos > (countNodes(root)) or pos<0){
        cout<<"\tError: The position that you are trying to use is invalid."<<endl;
        cout<<"\tThe list only have '"<<countNodes(root)<<"' elements. Try with one that is on range."<<endl;
    }
}

1 个答案:

答案 0 :(得分:0)

首先,我会在BST类中放入一个用于存储根目录的数据成员。

然后我会将您的busquedaPos()方法重新定义为以下内容:

void BST::busquedaPos(node * root, node *& found_node,
                   size_t & curr_pos, size_t pos)
  {
    if (root == nullptr)
      return;

    if (curr_pos == pos) // Is current root at the inorder position pos?
      {
        found_node = root;
        return;
      }

    ++curr_pos;
    busquedaPos(root->left, found_node, curr_pos, pos);
    ++curr_pos;
    busquedaPos(root->right, found_node, curr_pos, pos);
  }

然后你的类方法会使用(正如我设想的那样)这个静态方法。例如,recupera()可以这样实现:

int BST::recupera(size_t pos)
{
  node * found_node = nullptr;
  size_t curr_pos = 0;
  busquedaPos(root, found_node, curr_pos, pos);
  if (found_node != nullptr)
    return found_node->info;

  throw std::out_of_range("Position " + to_string(pos) +
              " greater or equal to number of nodes");
}

请注意,我已将int类型的位置更改为size_t,以避免验证否定职位(无法定义)。此外,recupera()的返回值是在顺序位置pos

中检索到的键