我正在学习树木。我刚刚完成问题,检查树是否完整BST。我想知道我是否做对了。 基本上我只需要为整棵树寻找一个只有一个孩子的节点。
编辑:当Mooing Duck指出时,我对完整和完整二进制搜索树的定义都是错误的。我现在完成了编码,这是解决方案吗? int heightBST(Node* root)
{
if (root == NULL)
{
return -1;
}
int lHeight = heightBST(root->left);
int rHeight = heightBST(root->right);
return lHeight > rHeight ? 1 + lHeight : 1 + rHeight;
}
int isFullBST(Node* root)
{
if (root == NULL)
{
return 1;
}
int lHeight = heightBST(root->left);
int rHeight = heightBST(root->right);
if (lHeight != rHeight)
{
return -1;
}
if ((root->left == NULL && root->right != NULL) || (root->left != NULL && root->right == NULL))
{
return 0;
}
if (isCompleteBST(root->left) == 0 || isCompleteBST(root->right) == 0)
{
return 0;
}
return 1;
}
int isCompleteBST(Node* root)
{
if (root == NULL)
{
return 1;
}
int lHeight = heightBST(root->left);
int rHeight = heightBST(root->right);
if (lHeight - rHeight != 0 || lHeight - rHeight != 1)
{
return 0;
}
if ((root->left == NULL && root->right != NULL) || (root->left != NULL && root->right == NULL))
{
return 0;
}
if (isCompleteST(root->left) == 0 || isCompleteBST(root->right) == 0)
{
return 0;
}
return 1;
}