二叉树搜索未返回预期值

时间:2015-09-30 19:56:41

标签: c++ binary-tree binary-search-tree binary-search

如果我有结构:

teemo/tags/__init__.py

添加功能:

struct node{
  int key_value;
  node * p_left;
  node * p_right;
};

以及搜索功能:

node* add(node * p_tree, int key) {
  //--The base case of the recursive function will be placed in here
  //--since binary trees are recursive in nature and linked data structures
  //--are as a whole in terms of space and memory, the recursive function will
  //--suffice for most cases involving binary trees.
  //--In this case, if the given parameter is null, we create the tree
  //--by allocating the necessary memory space
  if (p_tree == NULL) {
    node * pnew_tree = new node;
    pnew_tree->p_left = NULL;
    pnew_tree->p_right = NULL;
    pnew_tree->key_value = key;
    cout << "Added node: " << pnew_tree->key_value << endl;
    return pnew_tree;
  }// end of base case

  //--Depending of the value of the node, we determine if we will add to the left side or the right side of the subtree
  if (key < p_tree->key_value){
    // if it is less than the value, we add to the left
    p_tree->p_left = add(p_tree->p_left, key);
  }
  else{
    p_tree->p_right = add(p_tree->p_right, key);
  }
  return p_tree;
} // end of function

为什么我跑的时候:

node* search(node *p_tree, int key) {
  //--First:
  if (p_tree != NULL) { 
    if(key == p_tree->key_value){
      cout << "Node found" << endl;
      return p_tree;
    }
    if(key < p_tree->key_value){
      return search(p_tree->p_left, key);
    }
    else{
      return search(p_tree->p_right, key);
    }
  }
    else{
      return NULL;
    }


}//--End of recursive search function

输出是&#34;未找到节点&#34;而不是&#34; Node找到&#34; ? 据我所知add函数不返回NULL,为什么会这样呢? 我试着研究类似的问题,但是不能理解它们中的代码足以提出我自己的解决方案,我也不太熟悉使用我的IDE(代码块)调试,因此不知道去哪里。 (我只需要一个逻辑修复,因为我似乎无法在自己身上找到一个)

1 个答案:

答案 0 :(得分:1)

函数add返回指向二叉树树根的指针。通常这只是与函数参数p_tree相同的指针,因为二叉树的根永远不会改变。

但是在空树(p_tree == NULL)的情况下,add将返回指向新创建的树根的指针。因此,您必须更新变量myBinaryTree。执行后

node* myBinaryTree = NULL;
add(myBinaryTree,1);

变量myBinaryTree仍然具有值NULL。您还没有将其更新到树的根目录。以下代码有效:

node* myBinaryTree = NULL;
myBinaryTree = add(myBinaryTree,1);
cout << "Testing to see if it is there" << endl;
if (search(myBinaryTree,1) == NULL) {
    cout << "Node not found" << endl;
}