题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。如果是返回true,否则返回false。
例如输入5、7、6、9、11、10、8,由于这一整数序列是如下树的后序遍历结果:
8
/ \
6 10
/ \ / \
5 7 9 11
因此返回true。
如果输入7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回false。
树的题目一般都是递归的思路,因为是因为是排序树,而且是后序,所以思路是序列最后一个必是根节点,从前往后遍历,比根节点小的都是其左子树,并且位于序列的左半部分,比其大的为其右子树,应该位于其右半部分。左右子树按上述思路分别进行判断。
树的题目一般都是递归的思路,因为是因为是排序树,而且是后序,所以思路是序列最后一个必是根节点,从前往后遍历,比根节点小的都是其左子树,并且位于序列的左半部分,比其大的为其右子树,应该位于其右半部分。左右子树按上述思路分别进行判断。
#include "iostream"
using namespace std;
bool isPost(int a[],int start ,int end){
int root = a[end];
int left = start;
while(a[left]<root) left++;
for (int i = left; i < end; ++i)
{
if(a[i]<root) return false;
}
bool left_isPost = true;
bool right_isPost = true;
if(left > 0) left_isPost = isPost(a,0,left-1);//遍历左子树
if(left < end -1 ) right_isPost = isPost(a,left,end-1);//遍历右子树
return left_isPost&&right_isPost;
}
int main(int argc, char const *argv[])
{
bool flag;
int a[]={5,7,6,9,11,10,8};
flag = isPost(a,0,sizeof(a)/sizeof(int)-1);
if(flag) cout<<"yes"<<endl;
else cout<<"no"<<endl;
int b[]={7,4,6,5};
flag = isPost(b,0,sizeof(b)/sizeof(int)-1);
if(flag) cout<<"yes"<<endl;
else cout<<"no"<<endl;
return 0;
}
http://www.cnblogs.com/aLittleBitCool/archive/2011/01/19/1939683.html