面试题24:二叉搜索树的后序遍历序列

来源:互联网 发布:散打教学软件 编辑:程序博客网 时间:2024/06/07 23:01

题目描述:
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。

思路:

1. 首先找到根节点,即最后一个元素

2. 从左向右遍历,找到左子树序列的终止位置,即第一个比root大的数的位置,该位置也是右子树序列的起始位置

3. 从右子树序列的起点开始遍历,如果找到右子树序列中有比root小的,直接返回false

4. 分别递归遍历左右子树序列,返回两者的与结果(left && right)

5. 注意,如果输入的是空序列,返回false;如果左右子树为空,则返回true

给出两种解题答案,主要是传入参数的不同。

一. 传入参数是vector

bool VerifySquenceOfBST(vector<int> sequence) {    return VerifySquenceOfBSTHelper(sequence, 0 , sequence.size()-1);}//start是序列起始位置(从0开始),end是序列终止位置bool VerifySquenceOfBSTHelper(vector<int> &sequence, int start, int end){    int length = end - start + 1;        //空树返回false    if(sequence.empty() || length <= 0)    {        return false;    }    //二叉排序树的根节点    int root = sequence[end];    //寻找左子树序列终点,即从左往右遍历第一个比root大的值    int left_end = start;    for(; left_end < end; ++left_end)    {        if(sequence[left_end] > root)        {            break;        }    }    //此时left_end指向右子树序列的起始    //判断右子树序列中是否有比root小的,有就直接返回false    int j = left_end;    for(; j < end; ++j)    {        if(sequence[j] < root)        {            return false;        }    }    //分别遍历左右子树,判断它们的后序序列是否是二叉排序树    bool left_flag = true;//左子树为空,左子树返回true,右子树相同    int left_length = left_end - start;    if(left_length > 0)    {        left_flag = VerifySquenceOfBSTHelper(sequence, start, left_end-1);    }    bool right_flag = true;    int right_length = end - left_end;    if(right_length > 0)    {        right_flag = VerifySquenceOfBSTHelper(sequence, left_end, end-1);    }     return left_flag && right_flag;}

线上oj网址:
https://www.nowcoder.com/practice/a861533d45854474ac791d90e447bafd?tpId=13&&tqId=11176&rp=1&ru=/activity/oj&qru=/ta/coding-interviews/question-ranking

二. 传入参数是指针,和数组长度

bool VerifyBSTByPostOrder(int* seq, int length){    //空树返回false    if(seq ==  NULL || length <= 0)    {        return false;    }    //二叉排序树的根节点    int root = seq[length-1];    //寻找左子树序列终点,即从左往右遍历第一个比root大的值    int left_end = 0;    for(; left_end < length-1; ++left_end)    {        if(seq[left_end] > root)        {            break;        }    }    //此时left_end指向右子树序列的起始    //判断右子树序列中是否有比root小的,有就直接返回false    int j = left_end;    for(; j < length-1; ++j)    {        if(seq[j] < root)        {            return false;        }    }    //遍历左子树序列    int left_length = left_end;    bool left_flag = true;    if(left_length > 0)    {        left_flag = VerifyBSTByPostOrder(seq, left_length);    }    //遍历右子树序列    int right_length = length-1-left_length;    bool right_flag = true;    if(right_length > 0)    {        right_flag = VerifyBSTByPostOrder(seq+left_end, right_length);    }    return left_flag && right_flag;}int main(){    int data[7] = {5,7,6,9,11,10,8};    bool ret = VerifyBSTByPostOrder(data, 7);    printf("%d\n", ret);    return 0;}
阅读全文
0 0