[c ++问题,具有检查树是否已满的功能

问题描述 投票:0回答:1

因此,我有一个功能来检查树是否已满(如果每个节点只有0个或2个孩子)。其他所有功能都起作用,而问题出在这一功能上(第二个功能只是调用辅助功能)。第一个用户输入字符串,然后按顺序排序(有效)。 char位置:len / 2变成root并递归调用以剩下其余的树(尝试显示的作品)。无论我提供什么字符串输入,在运行代码时,我都得到树未满。任何帮助表示赞赏。补充说明:如果注释行未注释,则问题会逆转,并且每次输入时我都会不断发现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;

}





c++ recursion binary-search-tree nodes
1个回答
0
投票

“ @ VictorNath您将l传递给函数sortedArrayToBST的值是什么?看来,在辅助函数的末尾是最后一个元素(而不是最后一个元素之后的元素)。 “ sortedArrayToBST的第二个参数。” -米哈伊尔

摘要解决方案是在调用sortedArrayBST时从长度中减去1

© www.soinside.com 2019 - 2024. All rights reserved.