C++ 二叉树中指向节点的解引用指针 #包括 使用名称空间std; 结构节点 { int键; 结构节点*左; 结构节点*右; 节点(int k){ key=k; 左=右=空; } }; int main(){ 节点*根=新节点(1); 根->左=新节点(2); 根->右=新节点(3); cout
必须为struct重载ostream运算符:C++ 二叉树中指向节点的解引用指针 #包括 使用名称空间std; 结构节点 { int键; 结构节点*左; 结构节点*右; 节点(int k){ key=k; 左=右=空; } }; int main(){ 节点*根=新节点(1); 根->左=新节点(2); 根->右=新节点(3); cout,c++,pointers,tree,dereference,C++,Pointers,Tree,Dereference,必须为struct重载ostream运算符: #include <bits/stdc++.h> using namespace std; struct Node { int key; struct Node *left; struct Node *right; Node(int k){ key=k; left=right=NULL; } }; int main() { Node *root=new Node(1); ro
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int key;
struct Node *left;
struct Node *right;
Node(int k){
key=k;
left=right=NULL;
}
};
int main() {
Node *root=new Node(1);
root->left=new Node(2);
root->right=new Node(3);
cout<<*root<<endl;
}
在你的代码中,你在哪里告诉它如何打印一个
节点
?谢谢。但是你能告诉我*root代表什么吗?如果我试图通过以下方式比较两个节点:*root!=*root1,它又抛出了一个错误。为什么会这样?我编辑了我的答案:)并再次编辑了它:D希望这足以让你现在理解:)
std::ostream& operator<<(std::ostream& os, const Node& node)
{
if (os.good())
{
os << node.key << std::endl;
// print pointer here if needed
// ...
}
}
cout << root->key << endl;
bool operator==(Node *lnode, Node *rnode)
{
return lnode->key == rnode->key;
}