【发布时间】:2019-12-17 01:20:13
【问题描述】:
class Node{
public:
friend class BinaryTreeAdd;
Node(int value, Node* left, Node* right)
{
this->value = value;
this->left = left;
this->right = right;
}
int getValue() const
{
return value;
}
Node* getLC() const
{
return left;
}
Node* getRC() const
{
return right;
}
void setValue(int value) {
this->value = value;
}
void setLC(Node* left) {
this->left = left;
}
void setRC(Node* right) {
this->right = right;
}
public:
int value;
Node* left;
Node* right;
};
class class BinaryTreeAdd {
public:
static Node* cpNode(const Node* source)
{
if (source == nullptr)
{
return nullptr;
}
return source == nullptr? nullptr
: new Node(source->value,
cpNode(source->left),
cpNode(source->right));
}
static Node* add(Node *t1, Node *t2){
if (t1 == NULL) {
return t2;
}
if (t2 == NULL) {
return t1;
}
t1->value += t2->value;
t1->left=add(t1->left, t2->left);
t1->right=add(t1->right, t2->right);
return t1;
}
void display(Node * node){
while (node != NULL) {
cout << node->getValue() << endl;
display(node->getLC());
display(node->getRC());
return;
}
}
};
int main(){
BinaryTreeAdd bt;
Node root1(3, NULL, NULL);
Node root2(1, &root1, NULL);
Node root3(3, NULL, NULL);
Node root4(5, &root2, &root3);
Node root5(5, NULL, NULL);
Node root6(6, NULL, &root5);
Node root7(5, NULL, NULL);
Node root8(2, &root6, &root7);
Node *root9 = BinaryTreeAdd::add(&root4, &root8);
Node *root10 = BinaryTreeAdd::cpNode(root9);
bt.display(root10);
return 0;
}
- 我已合并两棵树 t1 和 t2 并将结果存储回 t1 (添加功能)。 函数调用:Node *root9 = BinaryTreeAdd::add(&root4, &root8);
- 然后我将 t1 深度复制到源(cpNode 函数)。 函数调用:Node *root10 = BinaryTreeAdd::cpNode(root9);
- 我使用了显示功能来打印深拷贝的结果。 函数调用:bt.display(root10);
我的问题是:
如何使用cpNode函数将t1和t2的内容直接复制到源节点?
合并树后,t1 和 t2 的内容不应更改。
【问题讨论】:
-
这是一种非常奇怪的添加二叉树的方法。你确定你在做一些有意义的事情吗?
-
是的。我确定。
-
我在面试中遇到了这个问题。我无法解决它。所以我需要帮助来解决这个问题。
标签: c++ data-structures stl