void heapRebuild(int rootIndex, std::vector<int> &HEAP, int HEAP_SIZE){ //std::cout<<"heapRebuild_start\n"; if(!isLeaf(rootIndex, HEAP_SIZE)){ int largerChildIndex=(2*rootIndex)+1; if(hasRightChild(rootIndex, HEAP_SIZE)){ int rightChildIndex=largerChildIndex+1; if(HEAP[rightChildIndex]>HEAP[largerChildIndex]){ counter++; largerChildIndex=rightChildIndex; } } if(HEAP[rootIndex]<HEAP[largerChildIndex]){ counter++; int temp = HEAP[rootIndex]; HEAP[rootIndex]=HEAP[largerChildIndex]; HEAP[largerChildIndex]=temp; heapRebuild(largerChildIndex, HEAP, HEAP_SIZE); } } //std::cout<<"heapRebuild_end\n"; }
/* 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)) ); }