Reputation: 617
I have a question regarding the removing part from a binary search tree function.
switch (childCount){
case 0: // It has no children then remove parent
if(current.value < parent.value){
parent.left = null;
} else{
parent.right = null;
}
break;
case 1: //it has 1 children, reassign to parent
if(current.value < parent.value){
parent.left = (current.left === null ? current.right : curent.left);
} else {
parent.right = (current.left === null ? current.right : current.left);
}
break;
I'm not really understanding case 1, and the values for parent.left AND parent.right. What does the (current.left === null ? current.right : curent.left) exactly mean? The syntax is throwing me off. I know it refers to a case that if it has one child, just reassign to the parent. But I'm still confused
Thanks,
Upvotes: 0
Views: 62
Reputation: 417
So basically this is just saying that if the current node (the node we are trying to remove) has one and only one child we have to assign currents child to be a child of parent so we don't lose the child from the tree. As moller said, the assignments are ternary operators so if the test
parent.left = (current.left === null ? current.right : curent.left);
evaluates to true parent.left is set to current.right, otherwise it is set to current.left.
All these checks are to maintain the property of a binary search tree where left children are <= parent and right children are > than parent.
Upvotes: 1
Reputation: 2470
parent.left = (current.left === null ? current.right : curent.left);
means
if (current.left === null)
parent.left = current.right;
else
parent.left = curent.left;
see for detail: Wikipedia - ternary operator
Upvotes: 2