以下是我无法导致错误的示例代码。
#include<iostream>
using namespace std;
struct node
{
int value;
node* left;
node* right;
node* parent;
node()
{
}
node(int value)
{
this->value = value;
this->left = NULL;
this->right = NULL;
this->parent = NULL;
}
};
int coun = 0;
void check(node** root)
{
if(coun == 0)
{
coun++;
check(&((*root)->right));
}
else
{
node *parentOfCurrent,*childOfCurrent;
parentOfCurrent = (*root)->parent;
childOfCurrent = (*root)->right;
cout << "Value before the statement" << (*root) << "\n";
parentOfCurrent->right = childOfCurrent;
cout << "Value after the statement" << (*root) << "\n";
}
}
int main()
{
node *node1,*node2,*node3,*node4,**temp,*temp2;
node1 = new node(1);
node2 = new node(2);
node3 = new node(3);
cout << "Node1 Node2 Node3" << node1 << " " << node2 << " " << node3 << "\n";
node1->right = node2;
node2->right = node3;
node2->parent = node1;
node3->parent = node3;
check(&node1);
//cout << node2->value;
}
在这个例子中,我创建了一个树as descibed here 我在这里尝试将node1的右侧字段分配给node3。 我遵循的程序是:
parentOfCurrent->right = childOfCurrent
;
被执行。
此语句旨在将node1的.right字段分配给node3。发生的事情是声明不同之前和之后的*值。
Value before the statement: 0x9e17b8
Value after the statement: 0x9e6f30
正在发生的是指针 parentOfCurrent-&gt;右边(* root)被设置为childOfCurrent ,但我无法解释为什么发生这种情况?
答案 0 :(得分:1)
你有这个“树”:
1
/\
x 2
/\
x 3
当您输入递归时,root
保存1
右指针的地址。
1
/\
x 2 <-- *root (root == &node1->right)
/\
x 3
parentOfCurrent->right
指向1
的正确孩子(其值与*root
相同)。
childOfCurrent
指向3
节点。
分配后,root
仍然是1
右指针的地址,但1
的右子项现在是3
节点:
1
/\
x 3 <-- *root (root == &node1->right)
/\
x x
这里似乎没有双指针间接 试试这个:
void check(node* root)
{
if(coun==0)
{
coun++;
check(root->right);
}
else
{
node *parentOfCurrent, *childOfCurrent;
parentOfCurrent = root->parent;
childOfCurrent = root->right;
cout<<"Value before the statement"<<root<<"\n";
parentOfCurrent->right = childOfCurrent;
cout<<"Value after the statement"<<root<<"\n";
}
}
int main()
{
node *node1,*node2,*node3;
node1 = new node(1);
node2 = new node(2);
node3 = new node(3);
cout<<"Node1 Node2 Node3"<<node1<<" "<<node2<<" "<<node3<<"\n";
node1->right = node2;
node2->right = node3;
node2->parent = node1;
node3->parent = node2; // You had a bug here, making node3 its own parent.
check(node1);
cout << node1->right->value; // Prints 3
}
请注意,您还需要调整正在移动的节点的父指针,但我将其删除了。