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;
}

Similar Messages

  • 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

  • Is there any way to get the height/width of an image before importing it in the indesign document.

    Hi All,
    I need to obtain an image's attributes such as dimensions (height, width in pixels) without placing image in indesign document.
    I have full path of the image (say abc.jpg is stored at c:\my pic\abc.jpg).
    I have obtained the IDFile for this image, tried getting size using GetFileSize() which correctly return size in bytes.
    Is there any way to get the height/width of image without importing it in the indesign document.
    Please, give me some hints. I have spent quite a lot time digging in CHM. I have searched in FileUtils, IDFile API's but found no method which serves this purpose.
    At this point I am clueless where to search next.
    Any help will be appriciated.
    Just a point to mention, I am able to get image height and width for an image in indesign doc though Its not my requirement.
    Thnx,
    D.

    You might be able to examine the contents of the PlaceGun after calling kImportAndLoadPlaceGunCmdBoss without actually placing the image in a document. Not sure, but would be worth looking at.
    Otherwise you will probably have to write platform specific code, ideally with a generic platform-independant wrapper (see SDKSamples/paneltreeview/PlatformFileSystemIterator).
    For the Mac, look at CGImageGetWidth() etc., not sure what the best option is for windows.
    Perhaps Quicktime could provide you with a platform independant solution.

  • How to get the root node of a tree?

    I wanna get all the leaf node of a tree.But JTree have no method about how to get the root TreeNode of a tree.Then how should I do?

    try this:
    http://javaalmanac.com/egs/javax.swing.tree/GetNodes.html?l=rel

  • How can I get the height of an UIComponent programmatically?

    How can I get the height of an UIComponent programmatically? In my case the component is a Panel Box which has bindings to a backing bean. But it seems the RichPanelBox does not have have method like getHeight()

    Use setInlineStyle(java.lang.String inlineStyle) method.
    RichPanelBox panelBox;
    panelBox.setInlineStyle("height:400px");
    Thanks,
    Navaneeth

  • Getting the height of the title bar of a JInternalframe

    Hi,
    How can i get the height of the title bar of a JInternalframe??
    Please reply asap.
    Thanks
    Jatin

    Try this.
    myFrame.getUI().getNorthPane().getHeight();

  • Getting the Height of Android Status Bar

    Hello,
    is it possible to get the Height of Android Status Bar ?
    thanks

    Hi Shongrunden,
    The above solution will not work when testing on the desktop as Capabilities.screenResolutionY returns the actual screen resolution of the host machine and not that of the emulated device.
    I too would really appreciate a method to obtain the devices status bar height (i.e Capabilities.statusBarHeight) for calulating component width and height upfront.
    Regards,
    Scott.

  • Get the height of a report to use for setting height of subreport

    I am getting an error:  Invalid Section Height   on one of my subreports
    that I am programmatically inserting into a report.  I have not set the
    subreport height, I thought that it would be automatically set if I didn't
    set it.   I am measuring the width of a section in the report I am using
    for a subreport to use as the Width for the subreport, but not sure how
    to get the height of the report.   It appears this needs to be in pixels.
    I have manually tried setting it to 14400, which I believe is 11" and I ge an invalid section height error.
    How do I get the height for the subreport???  
    I am using VB.Net 2008, Crystal 2008, Vista Buisiness.   - All the latest service packs of everything.
    Thanks,
    Jeff

    Hi Jeff,
    The easiest way to figure this out is to test it in the Crystal Reprot Designer first. Bascially you can't set the subreport higth larger than the report page itself. CR needs to allocate space for the Page header and footer then Group header/footer and detail sections. There are options when designing this in CR Designer which will allow you to span more than one page. The simplest way is to design a template report in Crystal Report Designer so you can see all the options required to make this work. Then you can set the same in code when inserting.
    Remember "If it can't be done in the Report Designer it can't be done in code" The Designer uses the same set of API's as .NET. By using a test report you can then see what settings are being configured when you get the info in code.
    It believe you simply need to set the Can Grow options. Test this in the Designer then update us if you have any more questions.
    Thank you

  • Problem getting the height of a UIScrollView

    hi,
    i am setting the size of a UIScrollView in viewDidLoad: but when I try to get the height of it, i am getting 0 in the console
    here is my code:
    - (void)viewDidLoad {
    [scrollView setContentSize:CGSizeMake(320,500)];
    NSLog(@"scrollView: %@", scrollView);
    NSLog(@"scrollView.contentSize.height: %i", scrollView.contentSize.height);
    [super viewDidLoad];
    and in the console log i get
    scrollView: <UIScrollView: 0x4974110; frame = (0 0; 320 367); clipsToBounds = YES; autoresize = RM+TM; layer = <CALayer: 0x4974010>>
    scrollView.contentSize.height: 0
    Shouldn't scrollView.contentSize.height be returning 367? On a related note, i specified the height to be 500 via [scrollView setContentSize:CGSizeMake(320,500)] , but that doesn't appear to be applied either?

    The width and height of CGSize are CGFloat type (double), so use a float format specifier in NSLog. E.g.:
    NSLog(@"scrollView.contentSize.height: %2.0f", scrollView.contentSize.height);
    - Ray

  • Getting the height of a font

    Hi there,
    I have a problem in determining the exact height of a font.
    I am using a JPanel to display some text in a GUI. The panel should have space for five lines of text. How can I determine the size of the font before the Frame that is containing my GUI is shown, so that I can set the size of the JPanel to the appropriate size?
    I've tried
    FontMetrics metrics = getFontMetrics(getFont());
    int lineHeight = metrics.getAscent() + metrics.getDescent();
    But this produces a NullPointerException on runtime.
    Does anyone know another way to get the height of a font before the frame is shown?
    Thank you,
    FReAK

    Ok,
    I figured out that the problem is that getFont() gets null as font.
    So if I use setFont() everything is fine.
    But I don't have to set a specific Font when drawing a String, so is there must be a standard Font.
    Does anyone know how to get the metrics of this font?

  • How to get the height of JPanel?

    Hi.
    I am new to GUI programming.
    I am trying to get the height of a JPanel which I put inside a JFrame but the getHeight() method returns me zero.
    My code are as follows:
    public class Form2
    public static void main(String[] args)
    JFrame f = new JFrame();
    JPanel p = new JPanel();
    f.setTitle("Testing...");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(400, 300);
    f.setVisible(true);
    f.add(p);
    System.out.println(f.getHeight());
    System.out.println(p.getHeight());
    Can somebody enlighten me on how to obtain the height of the JPanel?
    Thanks in advance.

    Swing related questions should be posted in the Swing forum.
    I am trying to get the height of a JPanelComponents don't have a size until the JFrame is made visible and all the components are layed out by the LayoutManager. You can use a WindowListener to tell when a frame is shown.

  • Who to get the height of the text in a Text Layout?

    Hey, I'm using the text layout component offered by adobe labs. I read the documentation and now capable of doing almost all what I need. I just have a small problem. Lets say I have a text layout object on my stage containing some text. How can I know the height of the text or the number of lines in it ???
    I found their is a porperty: "contentHeight"  and a method "calculateHeight()" but they are in another class of the libraries that comes with the text layout component. I don't know how to reach them. Please help and write me the lines of code that do this job.
    Thanks

    Well I was going to suggest that you post in the TLF forums, http://forums.adobe.com/community/labs/textlayout.
    But you seem to have found those. So instead I will suggest that you don't cross-post.
    Really if anybody could answer that it would be the folks there. I know there isn't a lot of traffic in those forums, but that is because the TLF is really insanely complicated and it is still beta. But it looks like most questions there do get some kind of answer....

  • How to get the children for a selected tree node?

    Hi,
    I want to get the number of child nodes for any selected node in JTree.
    How can i do this?
    Any help, greatly appreciated!!

    if you have a node already where aNode is a DefaultMutableTreeNode for example, then you can use that object's API method to get the child count.
    int childCount = aNode.getChildCount();
    If you want to loop through all of a node's children and do something at each node, the following may help:
    java.util.Enumeration e = aNode.children();
    while ( e.hasMoreElements() ) {
    DefaultMutableTreeNode n = (DefaultMutableTreeNode)e.nextElement();
    //Do something with n
    Hope this helps,
    Claire

  • MorseCode Binary Tree

    So I have an assignment to write a program that deciefers basic morse code using a binary tree. A file was provided with the information for the binary tree and I am using the text books author's version of BinaryTree class with a few methods of my own thrown in.
    For starters .. why would you ever use a tree for this .. just make a look up table. But my real problem is i keep getting null pointers at 38, 24, 55 and I have tried just about everything I know to do at this point. My mind is exhausted and I think I need a fresh pair of eyes to tell me what I have done wrong.
    I am sorry for such sloppy code.. I have been changing and rearranging too much.
    import java.io.*;
    import java.util.*;
    public class MorseCode extends BinaryTree{
         static BufferedReader in;
         static BinaryTree<String> bT = new BinaryTree<String>();
    /*     public static void loadTree() throws FileNotFoundException, IOException{
              in = new BufferedReader(new FileReader("MorseCode.txt"));
              bT = readBinaryTree(in);
         public static String decode(Character c) throws IOException{
              if(c.equals("null")){
                   return "";
              }else if(c.equals(" ")){
                   return " ";
              }else{
                   return (":" + find(c));
         public static String find(Character c) throws IOException, FileNotFoundException{
              in = new BufferedReader(new FileReader("MorseCode.txt"));
              bT = readBinaryTree(in);
              Queue<BinaryTree> data = new LinkedList<BinaryTree>();
              BinaryTree<String> tempTree = bT;
              String temp = null;
              Character tempChar = null;
              data.offer(tempTree);
              while(!data.isEmpty()){
                   tempTree = data.poll();
                   temp = tempTree.getData();
                   tempChar = temp.charAt(0);
                   if(tempChar.equals(c)){
                        break;
                   data.offer(tempTree.getRightSubtree());
                   data.offer(tempTree.getLeftSubtree());
              return temp.substring(2);               
         public static void main(String[] args) throws FileNotFoundException, IOException{
              Scanner scan = new Scanner(new FileReader("encode.in.txt"));
              String s = "";
              String temp = "";
              while(scan.hasNextLine()){
                    temp = scan.nextLine();
                    for(int i = 0; i < temp.length(); i++){
                         s = s + decode(temp.charAt(i));
              System.out.println(s);
    /** Class for a binary tree that stores type E objects.
    *   @author Koffman and Wolfgang
    class BinaryTree <E> implements Serializable
      //===================================================
      /** Class to encapsulate a tree node. */
      protected static class Node <E> implements Serializable
        // Data Fields
        /** The information stored in this node. */
        protected E data;
        /** Reference to the left child. */
        protected Node <E> left;
        /** Reference to the right child. */
        protected Node <E> right;
        // Constructors
        /** Construct a node with given data and no children.
            @param data The data to store in this node
        public Node(E data) {
          this.data = data;
          left = null;
          right = null;
        // Methods
        /** Return a string representation of the node.
            @return A string representation of the data fields
        public String toString() {
          return data.toString();
      }//end inner class Node
      //===================================================
      // Data Field
      /** The root of the binary tree */
      protected Node <E> root;
      public BinaryTree()
        root = null;
      protected BinaryTree(Node <E> root)
        this.root = root;
      /** Constructs a new binary tree with data in its root,leftTree
          as its left subtree and rightTree as its right subtree.
      public BinaryTree(E data, BinaryTree <E> leftTree, BinaryTree <E> rightTree)
        root = new Node <E> (data);
        if (leftTree != null) {
          root.left = leftTree.root;
        else {
          root.left = null;
        if (rightTree != null) {
          root.right = rightTree.root;
        else {
          root.right = null;
      /** Return the left subtree.
          @return The left subtree or null if either the root or
          the left subtree is null
      public BinaryTree <E> getLeftSubtree() {
        if (root != null && root.left != null) {
          return new BinaryTree <E> (root.left);
        else {
          return null;
      /** Return the right sub-tree
            @return the right sub-tree or
            null if either the root or the
            right subtree is null.
        public BinaryTree<E> getRightSubtree() {
            if (root != null && root.right != null) {
                return new BinaryTree<E>(root.right);
            } else {
                return null;
         public String getData(){
              if(root.data == null){
                   return "null";
              }else{
                   return (String) root.data;
      /** Determine whether this tree is a leaf.
          @return true if the root has no children
      public boolean isLeaf() {
        return (root.left == null && root.right == null);
      public String toString() {
        StringBuilder sb = new StringBuilder();
        preOrderTraverse(root, 1, sb);
        return sb.toString();
      /** Perform a preorder traversal.
          @param node The local root
          @param depth The depth
          @param sb The string buffer to save the output
      private void preOrderTraverse(Node <E> node, int depth,
                                    StringBuilder sb) {
        for (int i = 1; i < depth; i++) {
          sb.append("  ");
        if (node == null) {
          sb.append("null\n");
        else {
          sb.append(node.toString());
          sb.append("\n");
          preOrderTraverse(node.left, depth + 1, sb);
          preOrderTraverse(node.right, depth + 1, sb);
      /** Method to read a binary tree.
          pre: The input consists of a preorder traversal
               of the binary tree. The line "null" indicates a null tree.
          @param bR The input file
          @return The binary tree
          @throws IOException If there is an input error
      public static BinaryTree<String> readBinaryTree(BufferedReader bR) throws IOException
        // Read a line and trim leading and trailing spaces.
        String data = bR.readLine().trim();
        if (data.equals("null")) {
          return null;
        else {
          BinaryTree < String > leftTree = readBinaryTree(bR);
          BinaryTree < String > rightTree = readBinaryTree(bR);
          return new BinaryTree < String > (data, leftTree, rightTree);
      }//readBinaryTree()
      /*Method to determine the height of a binary tree
        pre: The line "null" indicates a null tree.
          @param T The binary tree
          @return The height as integer
      public static int height(BinaryTree T){
            if(T == null){
               return 0;
          }else{
               return 1 +(int) (Math.max(height(T.getRightSubtree()), height(T.getLeftSubtree())));
      public static String preOrderTraversal(BinaryTree<String> T){
          String s = T.toString();
          String s2 = "";
          String temp = "";
          Scanner scan = new Scanner(s);
          while(scan.hasNextLine()){
               temp = scan.nextLine().trim();
               if(temp.equals("null")){
                   s2 = s2;
              }else{
                   s2 = s2 + " " + temp;
          return s2;
    }//class BinaryTree

    As well as warnerja's point, you say you keep getting these errors. Sometimes it's helpful when illustrating a problem to replace the file based input with input that comes from a given String. That way we all see the same behaviour under the same circumstances.
    public static void main(String[] args) throws FileNotFoundException, IOException{
        //Scanner scan = new Scanner(new FileReader("encode.in.txt"));
        Scanner scan = new Scanner("whatever");The following isn't the cause of an NPE, but it might be allowing one to "slip through" (ie you think you've dealt with the null case when you haven't):
    public static String decode(Character c) throws IOException{
        if(c.equals("null")){
    c is a Character so it will never be the case that it is equal to the string n-u-l-l.
    Perhaps the behaviour of each of these methods needs to be (documented and) tested.

  • To display all the Nodes in a Binary Search Trees

    Hi,
    I want to traverse through all the nodes in a binary tree. I know that there are traversals like Preorder,Postorder,Inorder. But I am not able to write a recursive code for performing this operation. Can anyone please help me or give me an idea how to write a code to do any one of these traversal.
    Thanks a lot in advance.

    Hi,
    hmm .. how is a tree-node defined? - As so you have not posted a node-class, I will help you by demonstrating it for inOrder by normal language:
    The Idea is as follows:
    You have a root, that references to a tree-node. This tree-node has a value and 2 references to other tree-nodes, let's say they are named left and right. Because left an right are references to tree-nodes in the same way root is a reference to the tree-node, this fact can be used for recursive action on the tree.
    if you like to display all values in the tree, what do you have to do in a node?
    1. display the tree the left reference is pointing to
    2. display the value-Field
    3. display the tree the right reference is pointing to
    that is inOrder, assuming all lesser values are in the left tree and all greater are in the right tree.
    How to display the left and right trees?
    The same way you display this node, but this time you use the left / right reference as the node.
    So do it in pseudo-coding:
    void DisplayTree(NodeClass aNode) {
    if (aNode == null) return;
    DisplayTree(aNode.left);
    DisplayValue(aNode.value);
    DisplayTree(aNode.right);
    That is it - figure it out and try to write a program after this - good luck. To write one for pre-order and post-order should be easy if you have this one for inOrder.
    greetings Marsian

Maybe you are looking for