/*************************************************ios
判断整数序列是否是二元查找树的后序遍历结果
题目:输入一个整数数组,判断该数组是否是某二元查找树的后序遍历的结果。
若是是返回true,不然返回false。数组
例如输入五、七、六、九、十一、十、8,因为这一整数序列是以下树的后序遍历结果:spa
8
/ \
6 10
/ \ / \
5 7 9 11
所以返回true。
若是输入七、四、六、5,没有哪棵树的后序遍历的结果是这个序列,所以返回false。code
/*************************************************排序
二叉排序树(Binary S ort Tree)或二叉查找树(Binary Search Tree)或者是一棵空树,或者是具备下列性质的二叉树:io
(1)若左子树不空,则左子树上全部结点的值均小于它的根结点的值;class
(2)若右子树不空,则右子树上全部结点的值均大于它的根结点的值;stream
(3)左、右子树也分别为二叉排序树;二叉树
(4)没有键值相等的结点。遍历
后序遍历:左右根
分析:
一、后序遍历的最后一个节点是根节点;
#include <iostream> using namespace std; /* typedef struct BSTreeNode{ int data; BSTreeNode *left; BSTreeNode *right; }BSTreeNode,*BSTree; */ //判断给定序列是不是排序二叉树的后序遍历输出 int is_backsort(int *a,int start,int end){ if(start>=end){ return 0; } int root=a[end]; int i=start; int j=end-1; if(i<j){ while(a[i]<root && i<j){ i++; } while(a[j]>root && i<j){ j--; } } //cout<<"i:"<<i<<a[i]<<"j:"<<j<<a[j]<<endl; if(i<j){ return -1; } is_backsort(a,start,i-1); is_backsort(a,i+1,end); return 0; } int main(){ int a[]={5,7,6,9,11,10,8}; for(int i=0;i<=6;i++){ cout<<a[i]<<" "; } cout<<endl; int ret=is_backsort(a,0,6); cout<<"ret:"<<ret<<endl; }