The problem is very likely due to your initialisation of the struct binTreeNode
instances. Unlike languages such as Java or Python, C++ does not always initialise all attributes/members to zero, but rather depends on semantics when to do it.
So, what is happening under the hood?
When you call new your_type;
, the operating system hands you a piece of memory. The only guarantee you get, is that the allocated memory is at least the size of your_type
. If you're (very¹⁰) lucky, the piece of memory is set to zero. It is more likely, however, that this piece of memory was previously used (and freed) by another process, which wrote to it. Thus it contains random data.
In practice, this means, that binTreeNode->left
MIGHT be NULL
, but this is not guaranteed. Same goes for binTreeNode->right
.
How to fix:
Define a constructor, that explicitly sets the initial values of your instance. For your case, something like this should be sufficient:
struct binTreeNode {
int id;
binTreeNode* left;
binTreeNode* right;
binTreeNode()
: id{0}
, left{NULL}
, right{NULL}
{}
};
If you never heard of constructors (just in case):
Constructors are special methods, which are called when creating a new instance of a type.
As a additional side note, instead of NULL
use nullptr
, which was introduced in C++11.