title: How can I implement downHeap() function in a min-heap?
body: <p>I'm trying to write downHeap() function for a min-heap where I will check to see if a root node's child is less than the rootnode and if so, I will swap their values. The class Node is already defined for me and has a 'left' and 'right' child ptrs as well as 'value'. Below is my code so far:</p>
  <pre><code>void downHeap(Node *n) {
  
      if (!n) {return;}
  
      if (!n-&gt;left &amp;&amp; !n-&gt;right) {return;}
  
      if (n-&gt;left &amp;&amp; n-&gt;right){
          if (n-&gt;left-&gt;value &lt; n-&gt;right-&gt;value){
            if (n-&gt;left-&gt;value &lt; n-&gt;value){
              std::swap(n-&gt;value, n-&gt;left-&gt;value);
              downHeap(n-&gt;left);
            }
        else if (n-&gt;right-&gt;value &lt; n-&gt;left-&gt;value){
            if (n-&gt;right-&gt;value &lt; n-&gt;value){
              std::swap(n-&gt;value, n-&gt;right-&gt;value);
              downHeap(n-&gt;right);
            }
          }
        }
      }
  </code></pre>
  <p>This is my main to test the function:</p>
  <pre><code>int main() {
    Node *n = new Node(7);
    n-&gt;left = new Node(6);
    n-&gt;right = new Node(9);
    n-&gt;left-&gt;left = new Node(4);
    n-&gt;left-&gt;right = new Node(5);
    downHeap(n);
    printTreeVertical(n);
  
    delete n;
    n = nullptr;
    return 0;
  }
  </code></pre>
  <p>And my resulting tree:</p>
  <pre><code>##6 (X) Greater than child value 4
  #|
  #|_ 4.  // 4 is left child and 9 is right child of 6 in this tree.
  #|..|
  #|..|_ 7 //7 and 5 are children of 4.
  #|..|..|
  #|..|..|_ [null]
  #|..|..|
  #|..|..|_ [null]
  #|..|
  #|..|_ 5
  #|.....|
  #|.....|_ [null]
  #|.....|
  #|.....|_ [null]
  #|
  #|_ 9
  #...|
  #...|_ [null]
  #...|
  #...|_ [null]
  </code></pre>
  <p>As you can see 6 is the rootNode whereas 4 should be. And then 4 and 5 should swap places again. My function right now seems to swap the rootNode only once and keeps going down but does not recheck from the start. I've tried to add <code>downHeap(n)</code> again at the end of the if conditions but if I do that, nothing outputs. Please help!</p>