[英]How do I write this node counter?
嗨,我正在嘗試創建一個計算二進制樹中節點數的函數。 我收到一個錯誤消息,提示功能不匹配。 我遇到了其他錯誤,似乎無法正常工作。 我知道這個想法很難解決。 謝謝! 編輯-我的錯誤是參數列表不匹配。
template<class T>
class BinaryTree
{
private:
struct TreeNode
{
T value;
TreeNode *left;
TreeNode *right;
};
TreeNode *root;
void insert(TreeNode *&, TreeNode *&);
void NodeNumber(TreeNode *&, int&); //My NodeNumber declaration
public:
BinaryTree()
{
root = nullptr;
}
void insertNode(T);
int NodeNum();
};
template <class T>
void BinaryTree<T>::insertNode(T item)
{
TreeNode *newNode = nullptr;
newNode = new TreeNode;
newNode->value = item;
newNode->left = newNode->right = nullptr;
insert(root, newNode);
}
template <class T>
void BinaryTree<T>::NodeNumber(TreeNode *&root, int&)
{
if (root = nullptr)
return;
else
root->right;
root->left;
count = count + 2;
}
template <class T>
int BinaryTree<T>::NodeNum()
{
int count = 0;
NodeNumber(root,count);
return count;
}
在本課程中,您有許多錯誤的設計和錯誤。 我將專注於徹底的錯誤。 我不知道您的教授犯了哪些錯誤設計,哪個是您的錯誤設計。
當前寫入的BinaryTree<T>::NodeNumber
每次都會崩潰。 要弄清楚原因,請仔細考慮以下內容:
if (root = nullptr)
那條線與這兩條線有何不同?
root = nullptr;
if (root)
其次,這些行是什么:
root->left;
和:
root->right;
確切地做? 您為什么認為他們這樣做?
最后,您到底應該在什么時候添加count
,為什么? 那是真的嗎?
您沒有在此函數中為第二個參數命名,我認為應該是count
。
// original
template <class T>
void BinaryTree<T>::NodeNumber(TreeNode *&root, int&)
{
if (root = nullptr)
return;
else
root->right;
root->left;
count = count + 2;
}
一些評論:
如果您有一個非空的根指針,則要訪問左右兩個子樹。 看起來右邊在“其他”情況下看起來很奇怪,而左邊不是在這種情況下。 我建議擺脫“ else”,如果root為null則返回,否則在if之后左右處理。
您不測試根指針是否為空; 您將其設置為null。
沒有理由將引用傳遞給根指針
您的聲明,例如“ root-> right”,不會做任何事情。 您想向下遞歸左子項,然后向下遞歸右子項,因此需要再次調用NodeNumber並將您的孩子作為這些遞歸調用的根,同時也向下傳遞“ count”。
為什么要加2? 每個節點應僅計為1(遞歸向下時,其子節點將占自己的比例,因此僅為節點本身添加一個。)
我更喜歡返回計數而不是使用“ out”參數
因此,請考慮以下內容:
template <class T>
int BinaryTree<T>::NodeNumber(TreeNode *root)
{
if (root == nullptr)
return 0;
int count = 1;
count += NodeNumber(root->right);
count += NodeNumber(root->left);
return count;
}
當然,還要調整聲明並相應地調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.