Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use of double pointer instead of single pointer

I am working on a Binary search tree.

So,here is the structure used for representing the node:

typedef struct TreeNode
{
int num;
struct TreeNode *left,*right;
}TREENODE;

To insert a node in the tree I have the following method signatire

void InsertNode(TREENODE **root,int data);

In the above method why do we require double pointer.We can use a single pointer!

Are we using double pointer to avoid duplication?

like image 218
Anirudha Avatar asked Feb 21 '12 16:02

Anirudha


1 Answers

No, this is needed in case of rebalancing. After rebalancing root could be changed.

Ok, I will expand. Double pointer allows you to modify the pointer. So what is tree root in your case? Pointer to TREENODE. Some operations like search will never modify it. But some operations might need to change it, so that another node becomes new root. So they have to have access to that variable that you use as root. One example why they might need it is rebalancing, see AVL trees.

like image 144
Andrey Avatar answered Oct 16 '22 07:10

Andrey