下面的代码是将节点插入树中正确位置的函数。我不明白的是父节点实际代表什么。说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)。
现在root显然有5个。
root->left
为null,root->right
为null。如果现在插入2,则2将位于根的左侧。
所以root-> left将为2。现在简化一下,因为
root->left
表示节点,而不是值。因此
root->left->info = 2;
。现在还有另一件事要做。我们设置
root->left
的值。现在root->left
的父级是什么?那将是根所以
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.
关于c - 需要帮助来了解二进制搜索树中的父节点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27455262/