#include <iostream>
#include <stack>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <queue>
#include <string>
using namespace std;
//
// test.h
// test
//
// Created by 吴珝君 on 2018/12/31.
// Copyright © 2018年 闲着也是贤者. All rights reserved.
//
/************************************************************************/
/*
*/
//图的存储--邻接表
#define MAXSIZE 100
#define INF 65535
/************************************************************************/
void swap(int *arr,int L,int R)
{
int temp = arr[L];
arr[L] = arr[R];
arr[R] = temp;
}
//重要问题
int * generateRandomArray(int maxSize, int maxValue,int *size)
{
*size = rand()%maxSize + 1;//产生数组大小
int* arr = new int[*size];//产生1-maxvalue个元素的数组
for (int i = 0; i < *size; i++) {
arr[i] = (int) ( rand()%maxValue) - (int) (rand()%maxValue);//产生随机值
}
return arr;
}
/*
*/
/************************************************************************/
class BinaryTree
{
public:
BinaryTree(int d)
{
data = d;
left = NULL;
right = NULL;
parent =NULL;
};
int data;
BinaryTree *left;
BinaryTree *right;
BinaryTree *parent;
};
/************************************************************************/
/************************************************************************/
/* 判断一棵树是否是搜索二叉树 */
/************************************************************************/
bool IsBST(BinaryTree *root)
{
if (root == NULL)
{
return true;
}
if (root->left !=NULL && root->data > root->left->data&& root->right !=NULL && root->data < root->right->data||//左右子树不为空
root->left ==NULL && root->right !=NULL &&root->data < root->right->data ||//左空右不空
root->right==NULL && root->left!=NULL && root->left->data<root->data//右空左不空
||root->left==NULL && root->right == NULL)//左右都空
{
return IsBST(root->left)&&IsBST(root->right);
}
else
{
return false;
}
}
bool isCBT(BinaryTree *head)
{
//按照层次进行遍历
if (head == NULL)
{
return true;
}
BinaryTree *root = head;
queue<BinaryTree *> q;
q.push(head);
bool flag =false;
while(!q.empty())
{
root = q.front();
q.pop();
BinaryTree * l = root->left;
BinaryTree * r =root->right;
if ( flag &&( r!=NULL || l !=NULL )|| (l ==NULL && r !=NULL))
{
return false ;
}//我们从完全二叉树的特征出发: 如果出现某个非叶子节点 子树不全的时候,我们进行标记
//如果是完全二叉树,其后的节点一定没有左右子树 如果出现了有子树的情况 说明不是完全二叉树
if (l != NULL)
{
q.push(l);
}
if (r != NULL)
{
q.push(r);
}
else
{
flag = true;
}
}
return true;
}
int main()
{
BinaryTree* head = new BinaryTree(5);
head->left = new BinaryTree(3);
head->right = new BinaryTree(8);
head->left->left = new BinaryTree(2);
head->left->right = new BinaryTree(4);;
head->left->left->left = new BinaryTree(1);
head->right->left = new BinaryTree(7);
// head->right->left->left = new BinaryTree("6");
head->right->right = new BinaryTree(9);
head->right->right->left = new BinaryTree(9);
//head->right->right->right = new BinaryTree("11");
//string s =SerialBiTreeByPre(head);
// cout <<s<<endl;
//ReconbiTreeByPreString(s);
//preorder(head);
cout<<isCBT(head);
system("pause");
return 0;
}