A question on getting number of nodes in a Binary Tree

Posted by Robert on Stack Overflow See other posts from Stack Overflow or by Robert
Published on 2010-05-07T22:11:22Z Indexed on 2010/05/07 22:18 UTC
Read the original article Hit count: 170

Filed under:

Dear all,

I have written up two functions (pseudo code) for calculation the number of nodes and the tree height of a Binary Tree,given the root of the tree. Most importantly,the Binary Tree is represented as the First chiled/next sibling format.

so

struct TreeNode
{
  Object element;
  TreeNode *firstChild;
  TreeNode *nextSibling;
}

Calculate the # of nodes:

public int countNode(TreeNode root)
{
     int count=0;
     while(root!=null)
     {
        root= root.firstChild;
        count++;
     }

      return count;
}

public int countHeight(TreeNode root)
{
     int height=0;
     while(root!=null)
     {
        root= root.nextSibling;
        height++;
     }

  return height;

}

This is one of the problem I saw on an algorithm book,and my solution above seems to have some problems,also I didn't quite get the points of using this First Child/right sibling representation of Binary Tree,could you guys give me some idea and feedback,please? Cheers!

© Stack Overflow or respective owner

Related posts about data-structures