void removeFromSubTree(TreeNode* &node,int value) { if (node == NULL) printf("no such an element."); else if (node -> value == value ) { if((isLeaf(node))||(hasOneChild(node))) { if (isLeaf(node)) { delete node; node = NULL; return; } if (hasOneChild(node)) { if(hasLeftChild(node)) { TreeNode* tmp = node->left; delete node; node = tmp; } else { TreeNode* tmp = node->right; delete node; node = tmp; } } } else { int tmp = popMostLeftValue(node->right); node->value = tmp; } } else if (value > node->value) return removeFromSubTree(node->right,value); else return removeFromSubTree(node->left,value); }
/* RECURSION ALERT: * This functions recursively bubbles down the new root after dequeueing until the binary * search tree is rebalanced. */ void HeapPriorityQueue::bubbleDownSwap(string* parent, int index, string* child, string** &elements){ /* BASE CASE: * We can stop swapping elements down as soon as the child is bigger than the parent element. */ if(child > parent || index > size()){ return; } /* RECURSIVE STEP: * If the parent is bigger than either of the children, we need to swap the parent with the child * it is smaller than. If both children are equal, we will automatically swap with the left child. */ if(hasLeftChild(index, elements)){ string* leftChild = elements[index * 2]; //If the left child is smaller than the parent, swap down. if(leftChild < parent){ //Obtain original values/ string* original = parent; parent = leftChild; //Swap the two. child = original; bubbleDownSwap(parent, index * 2, child, elements); } } if(hasRightChild(index, elements)){ string* rightChild = elements[index * 2 + 1]; if(rightChild < parent){ //Obtain original values. string* original = parent; parent = rightChild; //Swap the two. child = original; bubbleDownSwap(parent, index * 2 + 1, child, elements); } } }
bool isLeaf(TreeNode* &node) { return (!hasLeftChild(node) && !hasRightChild(node)); }
bool hasOneChild(TreeNode* &node) { return ((hasLeftChild(node)) && !(hasRightChild(node))) || ( !(hasLeftChild(node)) && (hasRightChild(node)) ); }