/*
之前写的二叉树都是自己暴力创建的 这回写一个可以递归创建的 然后用-1表示NULL
*/
#include<iostream>
#include<cstdio>
using namespace std;
struct BinaryTreeNode
{
int data;
BinaryTreeNode * leftchild;
BinaryTreeNode * rightchild;
BinaryTreeNode(){}
};
/*
这里改了一个很牛叉的bug啊,看来自己没白努力,
一开始参数是BinaryTreeNode * root
结果这个函数结束后 发现 main函数的root还是NULL
突然想到 只是把NULL 赋值给了形参,可以通过返回值的形式
也可以通过指针的指针, 注意 (*root) 先加括号 再对后面的->
*/
void CreateBinaryTree(BinaryTreeNode ** root)
{
*root=new BinaryTreeNode();
printf("input the data\n");
int data;
scanf("%d",&data);
if(data==-1)
{
*root=NULL;
return ;
}
else
(*root)->data=data;
printf("Create left child of Node %d\n",(*root)->data);
CreateBinaryTree(&(*root)->leftchild);
printf("Create right child of Node %d\n",(*root)->data);
CreateBinaryTree(&(*root)->rightchild);
}
void PostOrderTravel(BinaryTreeNode * root)
{
if(root==NULL)
return ;
PostOrderTravel(root->leftchild);
PostOrderTravel(root->rightchild);
printf("%d ",root->data);
}
/*
这个函数其实想一下后序遍历的规律就很简单了。最后一个节点是根节点 然后前面左部分 比他小的是左子树
右部分比他大的是右子树 找到右子树的第一个元素 后面必须全比他大 如果不是的话 就直接false
然后再递归的看左右子树 左子树存在的条件是index》0 不存在就是true了
右子树类似 注意最后len的计算
*/
bool isOrderOfPostOfBST(int * arr,int len)
{
if(arr==NULL || len<=0)
return false;
int root=arr[len-1];
int index=0;//index 是左边 比root小的 的下标的前一个
for(;index<len-1;++index)
{
if(arr[index]>root)
break;
}
for(int j=index;j<len-1;++j)
{
if(arr[j]<root)
return false;
}
bool lefttrue=true;
if(index>0)
lefttrue=isOrderOfPostOfBST(arr,index);
bool righttrue=true;
if(index<len-1)
righttrue=isOrderOfPostOfBST(arr+index,len-index-1);
return lefttrue && righttrue;
}
int main()
{
//freopen("/home/gl/in","r",stdin);
int arr1[7]={5,7,6,9,11,10,8};
int arr2[4]={7,4,6,5};
//BinaryTreeNode * root=NULL;
//CreateBinaryTree(&root);
// cout<<endl;
//PostOrderTravel(root);
cout<<isOrderOfPostOfBST(arr1,7)<<endl;
cout<<isOrderOfPostOfBST(arr2,4)<<endl;
}