Question about snippet from binary search tree

I am wondering why the constructor for the binary search tree would want to give left node and right node a nullptr? Does this happen everytime I call a new node in the binary tree? I really don't see how the nodes are then connected. Much appreciated if anyone could please explain this to me.

1
2
3
4
5
6
  struct node {
	int value;
	node* left;
	node* right;
	node(int v) : value(v), left(nullptr), right(nullptr) { }
};
Last edited on
It's just initialized with null pointers. Later on the code will set them to the addresses of new nodes if they belong under this one.
nullptr is just used as a starting value. If you're creating a leaf node, then that's just what you need. But if you're creating a node that has left and (or) right child, then you change those pointers. For example:

1
2
3
4
5
node *leaf1 = new node(2);
node *leaf2 = new node(3);
node *root = new node(1);
root->left = leaf1;
root->right = leaf2;
Nodes are just clueless actors in a giant play. They know nothing. They need a director/manager who creates them, tells them who they're working with, and kills them without making a mess.
Last edited on
Topic archived. No new replies allowed.