[英]Need help understanding how using both a stack and binary search tree is relevant in an advanced Reverse Polish Notation program
[英]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.