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!