【问题标题】:C++ iterative insert into binary search tree BSTC ++迭代插入二叉搜索树BST
【发布时间】:2014-05-13 22:07:35
【问题描述】:

只要项目较小并因此插入左侧,我的功能就可以工作,但是当它应该向右移动时,似乎什么也没发生。它不会崩溃或其他任何事情,它只是不执行插入操作。

我不明白这是怎么发生的,因为在这两种情况下,代码中唯一的不同是单词 left 或 right(据我所知)。对于更有经验的人来说有什么明显的吗?

template <typename T>
void BST<T>::insertHelper(BST<T>::BinNodePtr &subRoot, const T& item)
{
  BinNode *newNode;
  BinNode *parent;
  BinNode *child;

  newNode = new BinNode;
  newNode->data = item;
  // newNode->left = NULL;
  // newNode->right = NULL;

  parent = subRoot;
  child = subRoot;

  if (!subRoot){
    subRoot = newNode;
  } else {

    if (item < child->data){
      child = child->left;
    } else if (item > child->data){
      child = child->right;
    }
    while (child){
      parent = child;
      if (item < child->data){
        child = child->left;
      } else if (item > child->data){
        child = child->right;
      }
    }
    child = newNode;
    if (child->data < parent->data)
      parent->left = child;
    else if (child->data < parent->data)
      parent->right = child;
  }
}

【问题讨论】:

  • 只需在这里和那里放一些printf() 调试输出来跟踪每个if 的决策是如何做出的,您会在最后一个if 子句中看到错误的决策。
  • if item == subRoot->data while 进入无限循环。你的测试用例中的 T 是什么? T 有一个比较运算符覆盖?

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


【解决方案1】:

您的最后一个“if”和“else if”具有相同的条件。第二个应该是'>'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    相关资源
    最近更新 更多