You have two options: constructor overloading, or default values for the optional parameters.
I am going to assume that the left
and right
constructor arguments should actually be pointers to nodes since you are building a tree. (I would suggest using std::unique_ptr
here but I'm going to just use raw pointers in this answer since it's not important to the answer to this particular question. However, I would strongly suggest investigating std::unique_ptr
since it will mean you won't need a custom destructor to delete child nodes; the smart pointer destructor will take care of that for you.)
Constructor overloading
Simply define multiple constructors that take all of the combinations you need:
public:
explicit TreeNode(T data);
TreeNode(T data, TreeNode * left);
TreeNode(T data, TreeNode * left, TreeNode * right);
You need to implement each constructor separately, but note that you can call one constructor from another using the constructor's initializer list.
Default values
public:
explicit TreeNode(T data, TreeNode * left = nullptr, TreeNode * right = nullptr);
(Substitute NULL
for nullptr
if you are not using C++11.)
In this case, left
and right
are optional parameters that will be "filled in" using the supplied defaults if they are omitted. (Note that you cannot omit only left
; if you omit left
you must also omit right
.)
When actually implementing the constructor you do not need to specify the default values again:
TreeNode::TreeNode(T data, TreeNode * left, TreeNode * right)
{
// ...
}
In both cases you will be able to call the constructor with one, two, or three arguments.