簡體   English   中英

需要幫助來了解二叉搜索樹中的父節點

[英]Need help understanding parent nodes in binary search trees

下面的代碼是將節點插入樹中正確位置的函數。 我不明白父節點實際上代表什么。 當它說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;
}

根據您的描述,我認為節點類是

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

現在在BST中將有一個根節點,其中父節點為NULL。 假設我們插入第一個值(設為5)。
現在根顯然有5個。 root->left為null, root->right為null。

如果現在插入2,則2將位於根的左側。

所以root-> left將為2。現在簡化一下,因為root->left表示節點,而不是值。 因此root->left->info = 2; 現在還有另一件事要做。 我們設置root->left的值。 現在root->left的父級是什么? 那將是root,所以root->left->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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM