0

Im creating a method to count the frequency of a value that is the methods parameter. I have created a binary tree and put values into it, im now trying to count all the values that equals the parameter. The problem is im getting a infinite loop, can anybody see why:

public int counter(T value)
  {
     if (value == null) return 0;
      Node<T> p = root, q = null; // q is the parent of p
      int values = 0;


    while (p != null)                           // checks p
    {
      int cmp = comp.compare(p.value,value);// compares

      if(p.value.equals(value))
      {
          values++;
      }

      if (cmp < 0) { q = p; p = p.left; }      // goes left in the tree
      else if (cmp > 0) { q = p; p = p.rigth; }  goes right in the tree


     if ( p == null) return values;
        }


      return 0; // if no values found in the tree 
  }

Constructor:

   private Node(T value, Node<T> l, Node<T> r) 
    {
      this.value = value;
      left = l; right = r;
    }
comodeque
  • 95
  • 1
  • 2
  • 7

2 Answers2

1

When you find a matching value you increment the counter but then don't change p, so you're stuck on the same node forever after that.

Any solution where the tree can contain more than one instance of a value is going to have to be recursive. Just draw a tree with, say, 6 instances of a particular value and walk through your code. You have to look at both subtrees at that point, so recursion is the only way to do this easily (or, you could use a parent-pointer stack as well, I suppose, but recursion is so much cleaner).

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
0

Thanks for the answers! Im not good at trees or recursive methods, but this is my try, im getting stack overflow so this is again a infinite loop. But I just dont know how to solve this.

 public int counter(T value)
  {
     if (value == null) return 0;
      Node<T> p = root, q = null;
      int countervalues = 0;

     if(p.value.equals(value))
      {
          countervalues++;
      }


  if(p.left!=null) p = p.left; counter(value);


  if(p.right!=null) counter(value);



     if(p.left == null && p.left == null)
         return countervalues;



      return 0;
  }
comodeque
  • 95
  • 1
  • 2
  • 7