【问题标题】:Need help understanding parent nodes in binary search trees需要帮助理解二叉搜索树中的父节点
【发布时间】:2015-02-11 20:24:04
【问题描述】:

以下代码是将节点插入树中正确位置的函数。我不明白的是父节点实际代表什么。当它说root -> left -> parent = root -> left时,它是什么意思?这不是将root的左父母设置为它自己吗? 不应该是root -> left -> parent = root,因为我们希望root的左孩子的父母是root而不是左孩子本身吗?能否请您为我澄清一下父节点,谢谢。

Node * insert(Node *root, int item) {
  if (root == NULL)
    return newNode(item);

  if (item <= root -> info)
    if (root -> left == NULL) {
      root -> left = newNode(item);
      root -> left -> parent = root -> left;      //**line of interest**
    }
    else
      insert(root -> left, item);
  else
    if (root -> right == NULL) {
      root -> right = newNode(item);
      root -> right -> parent = root -> right;
    }
    else
      insert(root -> right, item);
  return root;
}

【问题讨论】:

  • 这段代码工作正常吗?您的假设似乎是正确的:看起来像 root->left->parent = root;应该是命令。
  • @FernandoAires root-&gt;left-&gt;parent 不是 root 本身吗?
  • 这正是我写的...
  • @FernandoAires 该命令有原因吗?上面写着root = root...
  • 不是,就是把root的左指针指向的节点,把它的父指针设置为root的地址。

标签: c parent nodes binary-search-tree


【解决方案1】:

根据您的描述,我认为节点类将是,

class node{
   int info;
   node *left;
   node *right;
   node *parent;
};

现在在 BST 中将有一个根节点,其中的父节点将为 NULL。假设我们插入第一个值。(假设为 5)
现在 root 显然有 5 个。 root-&gt;left 为空,root-&gt;right 为空。

如果您现在插入 2,那么 2 将在根的左侧。

所以 root->left 将是 2。现在让我们简化一下,因为 root-&gt;left 我们的意思是一个节点,而不是一个值。 因此root-&gt;left-&gt;info = 2;。 现在还有一件事要做。我们设置root-&gt;left 的值。现在root-&gt;left 的父级是什么?那将是根, 所以root-&gt;left-&gt;parent = root;

现在如果你插入另一个数据(让它为 1)那么

root->left->left->info = 1;
root->left->left->parent = root->left;

所以你的代码没有简化在 BST 中插入节点的事情。

我会做的是,

 Node n = new node();
 n = newNode(item); //as you wrote
 n->parent = root->left.

【讨论】:

  • root-&gt;left 分配给n-&gt;parent 仅适用于root 比新插入的n 高两级的情况。还要注意root-&gt;left节点没有指向新的左节点,所以新节点还没有插入到树中,无法从根到达。
猜你喜欢
  • 2020-08-03
  • 2017-03-15
  • 2019-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多