判断序列是否是二叉查找树的后续遍历结果

题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。如果是返回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;
void test(int arr[],int start,int end,bool&flag)
{
    if(!flag || start >end) return;

    int left =start;
    while(arr[left]< arr[end]){
            left++;
    }

    int j= left;
    while(j<end) 
    {
        if(arr[j]< arr[end]) { flag =false; return;}
        j++;
    }

    test(arr,start,left-1,flag);
    test(arr,left,end-1,flag);
}

int main(void){
    bool flag=true;
    int a[]={1,2,5,4,3};
    test(a,0,6,flag);
    if(flag) cout<<"yes"<<endl;
    else cout<<"no"<<endl;
    int b[]={7,4,6,5};
    test(b,0,3,flag);
    if(flag) cout<<"yes"<<endl;
    else cout<<"no"<<endl;
    int x;
    std::cin>>x;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/writeeee/article/details/68957321