【发布时间】:2010-05-07 22:11:22
【问题描述】:
给定树的根,我编写了两个函数(伪代码)来计算二叉树的节点数和树高。 最重要的是,二叉树以 First chiled/next 兄弟格式表示。
所以
struct TreeNode
{
Object element;
TreeNode *firstChild;
TreeNode *nextSibling;
}
计算节点数:
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;
}
这是我在算法书上看到的问题之一,我上面的解决方案似乎有一些问题,我也不太明白使用二叉树的第一个孩子/右兄弟表示的要点,你能请大家给我一些想法和反馈,好吗? 干杯!
【问题讨论】:
标签: data-structures