我需要为二进制树类编写一个复制构造函数,该类会生成给定二进制树的深层副本,但是当我执行我的复制构造函数时,我总是遇到分段错误错误,更具体地说,父节点导致问题,但我无法弄清楚这样做的正确方法。
class Node
{
public:
int value;;
Node();
Node(int v);
Node * left;
Node * right;
Node * parent;
};
Node::Node()
{
left=nullptr;
right=nullptr;
parent=nullptr;
value=0;
}
Node::Node(int v)
{
val = v;
left = nullptr;
right = nullptr;
parent = nullptr;
}
class BT
{
public:
BT();
BT(const BTr & t);
Node *root;
int size;
Node * copy(Node *p);
//other functions..
};
BT::BT()
{
root = nullptr;
size = 0;
}
//No need to consider if t.root is nullptr here
//assume t is always a non-empty valid binary tree here
BT::BT(const BT &t)
{
size = t.size;
root = copy(t.root);
}
Node * BT::copy(Node *p)
{
if (p == nullptr)
{
return nullptr;
}
Node * n = new TNode(p->val);
n->left = copy(p->left);
n->left->parent = n;
n->right = copy(p->right);
n->right->parent = n;
return n;
}
int main()
{
BT y;
y.root = new Node(11);
y.root->left = new Node(12);
y.root->right = new Node(13);
y.root->left->left = new Node(14);
y.root->left->right = new Node(15);
y.root->right->left = new Node(16);
y.root->left->parent = y.root;
y.root->right->parent = y.root;
y.root->parent = nullptr;
y.root->left->left->parent = y.root->left;
y.root->left->right->parent = y.root->left;
y.root->right->left->parent = y.root->right;
y.size = 6;
BT b(y);
return 0;
}
答案 0 :(得分:1)
n->left->parent = n;
n->right->parent = n;
您未先检查left
或right
是nullptr
是否if(n->left) n->left->parent = n;
,而是执行这些作业。
添加支票:
right
同样适用于cordova.plugins.diagnostic.registerLocationStateChangeHandler(function(locationMode){
switch(locationMode){
case cordova.plugins.diagnostic.locationMode.HIGH_ACCURACY:
console.log("High accuracy");
break;
case cordova.plugins.diagnostic.locationMode.BATTERY_SAVING:
console.log("Battery saving");
break;
case cordova.plugins.diagnostic.locationMode.DEVICE_ONLY:
console.log("Device only");
break;
case cordova.plugins.diagnostic.locationMode.LOCATION_OFF:
console.log("Location off");
break;
}
});
。