面试100题:9.判断整数序列是不是二元查找树的后序遍历结果

来源:互联网 发布:ubuntu上安装输入法 编辑:程序博客网 时间:2024/04/30 11:51

转载并参考July的博客http://topic.csdn.net/u/20101126/10/b4f12a00-6280-492f-b785-cb6835a63dc9.html,万分感谢!

题目

输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。如果是返回true,否则返回false。

例如输入5, 7, 6, 9, 11, 10, 8,由于这一整数序列是如下树的后序遍历结果:

          8

      /      \

    6       10

  /  \      /    \

5     7  9    11

因此返回true。

如果输入7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回false。

分析

在后续遍历得到的序列中,最后一个元素为树的根结点。从头开始扫描这个序列,比根结点小的元素都应该位于序列的左半部分;从第一个大于跟结点开始到跟结点前面的一个元素为止,所有元素都应该大于跟结点,因为这部分元素对应的是树的右子树。根据这样的划分,把序列划分为左右两部分,我们递归地确认序列的左、右两部分是不是都是二元查找树。

解一

/*Title: 9.判断整数序列是不是二元查找树的后序遍历结果:解一Author:  gocodeDate:    2012-10-12*/ #include <iostream>using namespace std; bool verifyBSTPostSort(int squence[], int length){    // 判断数组是否为空或长度为0    if(squence == NULL || length <= 0)        return false;     // 后序排序二叉树的根节点是数组的最后一个,这是后序排序的特点    int root = squence[length - 1];     // 左子树的值永远要小于根节点,否则就可以判定该数组序列不是后序排序的二叉树    // squence[i]>root表明此时squence[i]进入右子树区间    int i = 0;    for(; i < length - 1; ++i)    {        if(squence[i] > root)            break;    }     // 右子树的值永远要大于根节点,否则就可以判定该数组序列不是后序排序的二叉树    // j = i 继续检查右子树    int j = i;    for(; j < length - 1; ++j)    {        if(squence[j] < root)            return false;    }     // 在区间点i,继续对两个区间检查    // left和right的初值不能设定为false,这是要考虑到区间为一个数值的情况。    // 区间为一个值时,上面2个for循环已经不起作用了,并且下面2个if语句为false    // 此时如果left,right的初值设为false,则区间为一个值时就会返回false,导致判断出错。    bool left = true;     if(i > 0)        left = verifyBSTPostSort(squence, i);     bool right = true;    if(i < length - 1)        right = verifyBSTPostSort(squence + i, length - i - 1);     return(left && right);} void main(){    int a[] = {5, 7, 6, 9, 11, 10, 8};     cout<<"The result is: "<<verifyBSTPostSort(a, 7)<<endl;    getchar();}

解二

/*Title: 9.判断整数序列是不是二元查找树的后序遍历结果:解二Author:  gocodeDate:    2012-10-12*/#include <iostream>#include <climits>using namespace std; #define N 100 bool judge(int a[], int len, int stk[]){    int top=1; //栈顶指针     for(int i=len-1; i>=0; --i)    {        if (a[i]>=stk[top]) //如果不能插入到栈中,返回false            return false;         while (a[i]<stk[top]) //在数组a[i]中查找第一个不大于stk[top]的数        {            --top;        }        if (a[i] == stk[top]) //如果啊a[i]与栈中元素相同返回false            return false;         // 把栈中比a[i]大的那个数向右移一个位置,把a[i]插到栈中        top += 2;        stk[top] = stk[top-1];        stk[top-1] = a[i];    }     return true;} int main(){    // INT_MAX = 2147483647    // INT_MIN = -2147483648    int stack[N]={INT_MIN, INT_MAX};    int a[]={5, 7, 6, 9, 11, 10, 8};        cout<<"The result is: "<<judge(a,7,stack)<<endl ;    cout<<"The stack is: "<<endl;    // 根据数组长度6列出栈内的值,顺序为栈顶到栈底    for(int j = 6; j >= 0; --j)        cout<<stack[j]<<" ";    getchar();}