so why did we pass node a and node b here as a pointers?? |
Ah that, I'm sorry for confusion!
Pointers unlike usual object variables point to memory location where the pointed objects lives.
When you pass a pointer you don't pass the real object but instead the memory address where those objects are, that is, a
memory location.
By using an asterisk
*
as in
*a
or
*b
, that asterisk returns the real object at that memory (not the address).
just saying
a
or
b
is a memory address, while
*a
or
*b
is the actual object in memory.
Why is this important for your function
bool areTreesIdentical(Node *a, Node *b)
?
It's important because of performance reasons, that function takes just memory address instead of real objects.
A memory address is just an
int
, however the real object is usually much bigger, that's why specifying the address is faster because copying memory address as function parameter (an int) is much faster than copying the whole object.
Conclusion:
An address being of size
int
is 2 or 4 bytes, while the real object
Node
can be much more bytes, therefore working with pointers is faster.
To be more precise, the size of an adress (pointer) is either 32 bits on x86 CPU, or 64 bits on x64 CPU.
In your example
a and
b are memory addresses, while
*a and
*b are real object at those memory locations.