试图自学 C++(我通常使用 Python)并编写了这段代码。
#include <iostream>
using namespace std;
class TreeNode {
public:
TreeNode *left;
TreeNode *right;
int value;
TreeNode(int _value);
void add_node(TreeNode node);
};
TreeNode::TreeNode(int _value) {
left = 0;
right = 0;
value = _value;
cout << "Creating node with value: " << value << endl;
}
void TreeNode::add_node(TreeNode node) {
cout << "Adding " << node.value << " to " << value << endl;
if (node.value < value) {
cout << node.value << " < " << value << endl;
if (left) {
cout << "Left node of " << value << " exists " << left->value << endl;
left->add_node(node);
} else {
cout << "Left node of " << value << " does not exist" << endl;
left = &node;
}
}
if (node.value > value) {
cout << node.value << " > " << value << endl;
if (right) {
cout << "Right node of " << value << " exists " << right->value << endl;
right->add_node(node);
} else {
cout << "Right node of " << value << " does not exist" << endl;
right = &node;
}
}
}
int main ()
{
TreeNode root(25);
TreeNode n1(15);
TreeNode n2(30);
TreeNode n3(20);
root.add_node(n1);
root.add_node(n2);
root.add_node(n3);
cout << root.left->value << endl;
cout << root.right->value << endl;
return 0;
}
该程序编译但运行结果我不明白。
Creating node with value: 25
Creating node with value: 15
Creating node with value: 30
Creating node with value: 20
Adding 15 to 25
15 < 25
Left node of 25 does not exist
Adding 30 to 25
30 > 25
Right node of 25 does not exist
Adding 20 to 25
20 < 25
Left node of 25 exists 20
Adding 20 to 20
20
20
我期待最后一点会有所不同。
Adding 20 to 25
20 < 25
Left node of 25 exists 15
Adding 20 to 15
20 > 15
Right node of 15 does not exist
15
30
有人可以解释这里发生了什么吗?