【发布时间】:2021-03-20 06:46:25
【问题描述】:
我正在回答hackerrank 上的一个编程问题,因此不允许使用类代码和后订购功能之外的任何内容。这个问题是一个简单的后序遍历问题。一段时间后我正在使用c ++,并且由于类结构是用一个指针作为二叉树的左右节点写出的,如果我试图找到一个树节点的邻居的值,他们碰巧是null,我会得到一个分段错误。
到目前为止,这是我的代码:
#include <bits/stdc++.h>
using namespace std;
/* you only have to complete the function given below.
Node is defined as
class Node {
public:
int data;
Node *left;
Node *right;
Node(int d) {
data = d;
left = NULL;
right = NULL;
}
};
*/
void postOrder(Node *root) {
if(root->left == nullptr && root->right == nullptr)
{
return;
}
postOrder(root->left);
postOrder(root->right);
cout << root->data << endl;
}
}; //End of Solution
我该如何解决这个问题?
【问题讨论】:
-
解决方法是:不要取消引用空指针。
-
检查
root而不是它的孩子。 -
#include <bits/stdc++.h>和using namespace std都是你应该立即改掉的两个习惯。使用您需要的标题。拥抱std::前缀。
标签: c++ class reference c++17 nullptr