Having trouble finding the height of a Binary Tree

Hi, I have an ADT class called DigitalTree that uses Nodes to form a binary tree; each subtree only has two children at most. Each node has a "key" that is just a long value and is placed in the correct position on the tree determined by its binary values. For the height, I'm having trouble getting an accurate height. With the data I'm using, I should get a height of 5 (I use an array of 9 values/nodes, in a form that creates a longest path of 5. The data I use is int[] ar = {75, 37, 13, 70, 75, 90, 15, 13, 2, 58, 24} ). Here is my code for the whole tree. If someone could provide some tips or clues to help me obtain the right height value, or if you see anything wrong with my code, it would be greatly aprpeciated. Thanks!
public class DigitalTree<E> implements Copyable
   private Node root;
   private int size;
   public DigitalTree()
       root = null;
       size = 0;
   public boolean add(long k)
       if(!contains(k))
            if(this.size == 0)
                root = new Node(k);
                size++;
                System.out.println(size + " " + k);
            else
                String bits = Long.toBinaryString(k);
                //System.out.println(bits);
                return add(k, bits, bits.length(), root);
            return true;
       else
           return false;
   private boolean add(long k, String bits, int index, Node parent)
       int lsb;
       try
           lsb = Integer.parseInt(bits.substring(index, index - 1));
       catch(StringIndexOutOfBoundsException e)
           lsb = 0;
       if(lsb == 0)
           if(parent.left == null)
               parent.left = new Node(k);
               size++;
               //System.out.println(size + " " + k);
               return true;
           else
               return add(k, bits, index-1, parent.left);
       else
           if(parent.right == null)
               parent.right = new Node(k);
               size++;
               //System.out.println(size + " " + k);
               return true;
           else
               return add(k, bits, index-1,  parent.right);
   public int height()
       int leftHeight = 0, rightHeight = 0;
       return getHeight(root, leftHeight, rightHeight);
   private int getHeight(Node currentNode, int leftHeight, int rightHeight)
       if(currentNode == null)
           return 0;
       //else
       //    return 1 + Math.max(getHeight(currentNode.right), getHeight(currentNode.left));
       if(currentNode.left == null)
           leftHeight = 0;
       else
           leftHeight = getHeight(currentNode.left, leftHeight, rightHeight);
       if(currentNode.right == null)
           return 1 + leftHeight;
       return 1 + Math.max(leftHeight, getHeight(currentNode.right, leftHeight, rightHeight));
   public int size()
       return size;
   public boolean contains(long k)
        String bits = Long.toBinaryString(k);
        return contains(k, root, bits, bits.length());
   private boolean contains(long k, Node currentNode, String bits, int index)
       int lsb;
       try
           lsb = Integer.parseInt(bits.substring(index, index - 1));
       catch(StringIndexOutOfBoundsException e)
           lsb = 0;
       if(currentNode == null)
           return false;
       else if(currentNode.key == k)
           return true;
       else
           if(lsb == 0)
               return contains(k, currentNode.left, bits, index-1);
           else
               return contains(k, currentNode.right, bits, index-1);
   public Node locate(long k)
        if(contains(k))
            String bits = Long.toBinaryString(k);
            return locate(k, root, bits, bits.length());
        else
            return null;
   private Node locate(long k, Node currentNode, String bits, int index)
       int lsb;
       try
           lsb = Integer.parseInt(bits.substring(index, index - 1));
       catch(StringIndexOutOfBoundsException e)
           lsb = 0;
       if(currentNode.key == k)
           return currentNode;
       else
           if(lsb == 0)
               return locate(k, currentNode.left, bits, index-1);
           else
               return locate(k, currentNode.right, bits, index-1);
   public Object clone()
       DigitalTree<E> treeClone = null;
       try
           treeClone = (DigitalTree<E>)super.clone();
       catch(CloneNotSupportedException e)
           throw new Error(e.toString());
       cloneNodes(treeClone, root, treeClone.root);
       return treeClone;
   private void cloneNodes(DigitalTree treeClone, Node currentNode, Node cloneNode)
       if(treeClone.size == 0)
           cloneNode = null;
           cloneNodes(treeClone, currentNode.left, cloneNode.left);
           cloneNodes(treeClone, currentNode.right, cloneNode.right);
       else if(currentNode != null)
           cloneNode = currentNode;
           cloneNodes(treeClone, currentNode.left, cloneNode.left);
           cloneNodes(treeClone, currentNode.right, cloneNode.right);
   public void printTree()
       System.out.println("Tree");
   private class Node<E>
      private long key;
      private E data;
      private Node left;
      private Node right;
      public Node(long k)
         key = k;
         data = null;
         left = null;
         right = null;
      public Node(long k, E d)
         key = k;
         data = d;
         left = null;
         right = null;
      public String toString()
         return "" + key;
}

You were on the right track with the part you commented out; first define a few things:
1) the height of an empty tree is nul (0);
2) the height of a tree is one more than the maximum of the heights of the left and right sub-trees.
This translates to Java as a recursive function like this:
int getHeight(Node node) {
   if (node == null) // definition #1
      return 0;   
   else // definition #2
      return 1+Math.max(getHeight(node.left), getHeight(node.right));
}kind regards,
Jos

Similar Messages

  • I'm having trouble finding the HEALTH magazine app for my iPad.  The mag insists that it has a free app.  Help!!

    I'm having trouble finding the HEALTH magazine app for my iPad.  The mag insists that it has a free app.  Help!!

    What country are you in ? Is this the app : Health magazine ?

  • I have Final Cut Pro X (10.0.9) and would like to change my project settings but I am having trouble finding the 'Modify Settings button.'  Where exactly is it located?

    I have Final Cut Pro X (10.0.9) and would like to change my project settings but I am having trouble finding the 'Modify Settings button.'  Where exactly is it located?  Here is the link which gives the instructions but doesn't seem to say where the 'Modify Settings Button' is located: http://support.apple.com/kb/PH12526?viewlocale=en_US

    You have to choose – one settigf or another.
    The thing is.your HD clips will look better in an SD project than your SD clips will in an HD project.
    WIthout knowing much more about your project and the kind of content, it's really hard to be specific. But generally I'd let my project settings be guided by what fraction of my timeline will be made up of HD clips and how much SD clips. If it's 75% HD, I'd probably do an HD project…and so on,
    Good luck.
    Russ

  • I am having trouble finding the Accept button for my licensing agreement and would like to accept.

    I am having trouble finding the Aceept button for my licensing agreement and would like to accept.

    Well, it's probably below the table... Sounds like you didn't consider the system requirements and installed on a system with too small screen resolution. If so, only using a larger res may possibly revela the magic button...
    Mylenium

  • For some reason I am having trouble finding the program

    I clicked Try and then It istalled stuff but at the end I could not find the program at all! It is not on my desktop or in programmes, why is this, have I done something wrong? Were could I find it ? Please help!

    It should be in the typical location.  Which operating system are you using exactly?  What Adobe software did you just install?

  • Getting the height of a binary tree

    So I am trying to create a method in my binary tree class that returns and integer that represents the height of the tree.
    I tried to do this recursively and it seems the numbers are close to the actual ones, but never exact and I haven't really been able to find out where the problem lies. This is my code:
    public int getHeight()
              int height;
              height = getHeightRecur(root);
              return height;
         public int getHeightRecur(BinTreeNode node)
              int theight;
              if(node == null)
                   theight = 0;
              else
                   theight = 1 + getMax(getHeightRecur(node.leftN), getHeightRecur(node.rightN));
              return theight;
         private int getMax(int x, int y)
              int result = 0;
              if(x>y)
                   result = x;
              if(y>x)
                   result = y;
              return result;
         }

    j2ee_ubuntu wrote:
    it may help at some extent..
    private int getMax(int x, int y)
              int result = 0;
              if(x>y)
                   result = x;
              else if(y>x)
                   result = y;
    else //when both are equal
    result =x; OR result = y;//You can use one of them
              return result;
         }Edited by: j2ee_ubuntu on Nov 6, 2008 12:30 AMWhy not just use [ Math.max|http://java.sun.com/javase/6/docs/api/java/lang/Math.html#max(int,%20int)] or write
    public static int max(int a, int b) {
        return (a >= b) ? a : b;
    }

  • I'm having trouble finding the music on my ipod touch!

    i've just updated my ipod to the newest software, now when i've unplugged it the music is unable to be shown on my ipod, however, i connect it to my computer and the music is there on my ipod playing! any suggestions or help without needing to restore my ipod to factory settings and losing everything?

    Was the content purchased from iTunes?  If not, it will not transfer.

  • I purchased Martha Stewart Living for IPad then realized it was free for me if I already received it in the mail. Now I need help in canceling the order and am having trouble finding the best way to do this easily and quickly. Please help.

    How can I most easily get refunded for subscribing to Martha Stewart Living on iPad in error?

    Normally there are no refunds, but you can try your luck.
    You can report issues with your iTunes Store purchases directly through the iTunes Store:
      http://support.apple.com/kb/HT1933

  • Add-On... Having trouble finding the correct add-on to use to view a video on a webpage.

    I am a photographer. I post videos on my blog for people to view as a slide show. I use animoto.com to create the slide shows and then copy and past the code onto my site. From my mobile device, wehere the video screen is, it tells me I need to use an add-on and to click there to download (which doens't allow an actual click). I went to the add-on area in firefox mobile but don't know which add-on to use.
    Thanks for your help in advance.

    The page uses Flash. We have our own page rendering core and making use of the Android Adobe Flash plugin has been difficult to implement.

  • Having trouble finding Character viewer

    I am having trouble finding the Character Viewer.  I've looked in the Launchpad and also in Finder under Applications.  If I accidentally sent it to the Trash and emptied it can I reinstall?
    OS X 10.8.5

    Actually I'm not looking for the Font Book , I'm looking for the Character Viewer.  FontBook I can find and it does not appear to give me what I want.  I was already using the Character Viewer quite a bit for a while, using it to find the pi sign, upside down exclamation points, fractions, foreign currency symbols and stuff like that.
    I suspect I turfed the app without realizing what I was doing at the time.  This is my first Mac and I am still acclimatizing to it.  Like I said, it can't be found in Finder under Applications so I'm thinking it must be missing.

  • Trouble finding the sampler in logic 8???

    Hello, I'm having trouble finding the esx24 sampler in logic 8. I see videos of people accessing it through the inspector menu on the left side of the screen under "inserts." I've looked several times through here and can't find it. I can't believe that I am already stumped. any help would be great

    nevermind, I found it. thanks

  • I need any help i can get, im having trouble with the app find my iphone. I have lost my iphone, checked on the computer, and somehow, took it away so how do i get it back??

    Help
    I need any help i can get, im having trouble with the app find my iphone. I have lost my iphone, checked on the computer, and somehow, took it away so how do i get it back??

    If you are saying that after signing into iCloud it is telling you device is not found, it could be for any number of reasons. If the battery is dead, if the SIM has been removed, or if someone else has the phone and they have restored it, it will not be shown. Also, if you located it once and then sent a remote wipe, it disables the abililty to locate the phone with Find My iPhone.

  • I am having trouble with the Jpeg icons and also now thumbnails not being visable in bith teh Apple finder and now also Adobe Bridge. Can anyone shed any light on this ?

    I am having trouble with the Jpeg icons and also now thumbnails not being visable in bith teh Apple finder and now also Adobe Bridge. Can anyone shed any light on this ?

    Argh - once again, I find my solution right after posting this. Left out one modification to the SWIG script, now it runs in 29 seconds vs C 16 seconds, I can live with that.

  • I want a soundbar for my 6th generation nano but am having trouble finding a compatible device. I'd like more than a dock, ideally a soundbar with wireless subwoofer. I'll only use the soundbar for music, not TV home theater. Any suggestions?

    I want a soundbar for my 6th generation nano but am having trouble finding a compatible device. I'd like more than a dock, ideally a soundbar with wireless subwoofer. I'll only use the soundbar for music, not TV home theater. Any suggestions? Thanks.

    Google

  • I'm having trouble finding carton hd on the app store

    I'm having trouble finding carton hd on the App Store

    Just a guess, are you looking for this:
    https://itunes.apple.com/us/app/cartoon-h.d-wallpapers/id535109714?mt=8

Maybe you are looking for