判断二叉树是否为搜索二叉树、完全二叉树、平衡二叉树:
搜索二叉树:若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值
完全二叉树:叶子结点只能出现在最下层和次下层,且最下层的叶子结点集中在树的左部
平衡二叉树:是一颗空树,或者左右子树高度差的绝对值不超过1
代码:
参考左神代码编写
#include <iostream>
#include <queue>
#include <cmath>
using namespace std;
struct Node
{
int value;
Node *left;
Node *right;
Node() : value(0), left(nullptr), right(nullptr) {}
Node(int x) : value(x), left(nullptr), right(nullptr) {}
Node(int x, Node *left, Node *right) : value(x), left(left), right(right) {}
};
/*
4
/ \
2 7
/ \ /
1 3 5
*/
void creat_bitree(Node *&head)
{
int in;
cout << "int put: ";
cin >> in; // 4 2 1 -1 -1 3 -1 -1 7 5 -1 -1 -1
if (in == -1)
{
head = nullptr;
}
else
{
head = new Node(in);
creat_bitree(head->left);
creat_bitree(head->right);
}
}
//判断是否为搜索二叉树
int comp_temp = INT_MIN;
bool is_BST(Node *head)
{
if (head == nullptr)
{
return true;
}
bool left_bst = is_BST(head->left);
if (!left_bst)
{
return false;
}
if (head->value <= comp_temp)
{
return false;
}
comp_temp = head->value;
return is_BST(head->right);
}
//判断是否为完全二叉树
bool is_CBT(Node *head) //利用层序遍历
{
if (head == nullptr)
{
return true;
}
queue<Node *> que;
que.push(head);
bool leaf = false; //标记第一个叶子结点,遇到第一个叶子结点后 leaf 一直为 true
while (!que.empty())
{
head = que.front();
Node *left = head->left;
Node *right = head->right;
que.pop();
if ((leaf && (left != nullptr || right != nullptr)) || (left == nullptr && right != nullptr))
{
return false;
}
if (left)
{
que.push(left);
}
if (right)
{
que.push(right);
}
else
{
leaf = true;
}
}
return true;
}
//判断是否为平衡二叉树
struct ReturnValue
{
int height;
bool isAVL;
ReturnValue() : height(0), isAVL(true) {}
ReturnValue(int x, bool yorn) : height(x), isAVL(yorn) {}
};
ReturnValue process(Node *head)
{
if (head == nullptr)
{
return ReturnValue(0, true);
}
ReturnValue left_is = process(head->left);
ReturnValue right_is = process(head->right);
int high = max(left_is.height, right_is.height) + 1;
bool is_balanced = left_is.isAVL && right_is.isAVL && abs(left_is.height - right_is.height) < 2;
return ReturnValue(high, is_balanced);
}
bool is_AVL(Node *head)
{
return process(head).isAVL;
}
//主函数
int main()
{
Node *root;
creat_bitree(root);
bool is_bst = is_BST(root);
bool is_cbt = is_CBT(root);
bool is_avl = is_AVL(root);
cout << "该树是否为BST? " << endl
<< (is_bst ? "yes" : "no") << endl;
cout << "该树是否为CBT? " << endl
<< (is_cbt ? "yes" : "no") << endl;
cout << "该树是否为AVL? " << endl
<< (is_avl ? "yes" : "no") << endl;
return 0;
}