我已經寫了兩個函數(僞代碼),用於計算樹的根節點數和二叉樹的樹高度。 最重要的是,二叉樹被表示爲第一個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;
}
這是我的一個算法書看到了問題的一個,和我上面的解決方案似乎有有些問題,我也沒有完全理解使用Binary Tree的First Child/Right兄弟表示的問題,請問您能給我一些想法和反饋嗎? 乾杯!
謝謝,托馬斯,我真的意識到我的錯誤在哪裏。我只是挑了兩個分支之一,忽略了另一個,這是可怕的! – Kevin 2010-05-07 22:34:14