title: How can I count the nodes of a data structure if a child has multiple parents?
body: <p>I need help with an assignement in java...so, I have a <code>TreeNode</code> class that looks like this...this is the way we were asked to do this so I am not allowed to change it.</p>
  
  <pre><code>class TreeNode{
  int data;
  TreeNode leftNode;
  TreeNode rightNode;
  public TreeNode(int data) {
       this.data=data;
  }
  </code></pre>
  
  <p>}</p>
  
  <p>The problem is that i have to create a method <code>int getNumOfNodes(TreeNode t)</code>  and will return the number of nodes in the structure.The thing is that i cannot figure out how to count the node with the value <code>9</code> only once since I am trying to use recursion for the left and right subtree and because this specific node has two parents it gets counted twice...Any ideas?</p>
  
  <p>I am trying to create this structure(I am trying to explain it since I couldn;t post a pic)</p>
  
  <pre><code>           5
           /  \
          7    12
           \  /  \
            9      2
  </code></pre>
  
  <p>here is what I tried</p>
  
  <pre><code> int getNumOfNodes (TreeNode t){
  
  
      if(t==null)
          return 0;
  
  
      return 1 + getNumOfNodes(t.leftNode) + getNumOfNodes(t.rightNode);
  }
  </code></pre>