So I'm working on implementing an insert method for a binary tree.
From what I can tell, the problem is that the changes made in the arguments of the function don't get properly returned back to main().
static void addChild(Child c, Child tree){
if(tree==null){
tree=c;
}
else{
if(c.cid>tree.cid){
addChild(c, tree.lc);
}
else if(c.cid<tree.cid){
addChild(c, tree.rc);
}
}
}
The Child objects seen above have nothing to do with the children of the nodes in the tree.
The tree nodes are Child objects.
cid is a field in the Child class which holds an integer.
rc is the right child of a node.
lc is the left child of a node.
Arguments of addChild:
@param Child c : the Child to insert into the tree
@param Child tree : the root of the tree
Basically my question is, shouldn't this be working correctly? When the method completes, the right child and left child of the tree given in the argument are null.
The recursive method only modifies the local copy on the stack.. Instead you should be passing a pointer or pass a reference to the tree nodes so that when u assign a child in the base case you make changes to the actual parent and not to the local copy (local copy gets destroyed after the function returns)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With