c++使用函数来检查树是否已满



所以我有一个函数来检查树是否是满的(如果每个节点只有0或2个子节点(。其他所有函数都能工作,而问题出在这个函数上(第二个函数只调用helper(。第一个用户输入字符串,然后按顺序进行排序(有效(。位于len/2位置的char被转换为根,并递归调用以生成树的其余部分(作品尝试显示(。当运行代码时,无论我提供什么字符串输入,我都会得到Tree未满。感谢您的帮助。另外注意:如果注释行被取消注释,问题就会逆转,我会不断地得到每个输入的Tree都是满的。如果需要,可以提供其他功能的代码。

我尝试过的输入:rats->arst(根节点r(不应该满victorn->cinortv(根节点o(应该是完整的

bool isFullTreehelper(TreeNode* R00t) 
{
//if empty tree then true
if (R00t == NULL)
return true;
//leaf node
if (R00t->left == NULL && R00t->right == NULL)
return true;
//if (R00t->left != NULL && R00t->right != NULL)
//return true;

if ((R00t->left != NULL) && (R00t->right != NULL))
return (isFullTreehelper(R00t->left) && isFullTreehelper(R00t->right));
return false;
}

//update: addditonal code (currently checking to see if this creates a balanced tree)
TreeNode* sortedArrayToBST_helper(ItemType items[], int start, int end)
{
// continue while this branch has values to process
if (start > end)
return NULL;
// Get the middle element and make it root
int mid = start + (end - start) / 2;
TreeNode* head = new TreeNode(items[mid]);
// Recursively construct the left subtree
// and make it left child of root
head->left = sortedArrayToBST_helper(items, start, mid - 1);
// Recursively construct the right subtree
// and make it right child of root
head->right = sortedArrayToBST_helper(items, mid + 1, end);
return head;
}
void TreeType::sortedArrayToBST(ItemType items[], int l)
{
root = sortedArrayToBST_helper(items, 0, l);
//debug lines
//cout << root->info << endl;
//cout << root->left->info << endl;
//cout << root->right->info << endl;
//cout << root->left->left->info << endl;
//cout << root->left->right->info << endl;
//cout << root->right->left->info << endl;
//cout << root->right->right->info << endl;
}


"@VictorNath你把什么值作为l传递给函数sortedArrayToBST?看起来,在辅助函数的末尾是最后一个元素(而不是最后一个之后的元素(。如果是这样,你应该把第二个参数中的项目大小减1传递给sortedArrayToBST。"-Michhail

总之,在调用sortedArrayBST 时,解决方案是从长度中减去1

最新更新