剑指offer33:二叉搜索树的后序遍历序列

题目描述

输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则返回true,否则返回false。假设输入的数组的任意两个数字都互不相同。
 
该题目两个隐藏的知识点:
1. 二叉搜索树(即二叉排序树)中序遍历序列即为该序列的一个有序序列,相当于题目中给出了一个中序遍历序列和一个后序遍历序列,那么我们可以唯一确定一颗二叉树
2. 树的遍历过程即一个出栈入栈的过程,因此,令一个序列为入栈序列,一个序列为出栈序列,利用《栈的压入、弹出序列》该题目的思想即可求解。
class Solution {
public:
    bool VerifySquenceOfBST(vector<int> sequence) {
        if(sequence.size()==0) return false;
        vector<int> inOrder(sequence);
        sort(inOrder.begin(),inOrder.end());
        stack<int> s;
        int j = 0;
        for(int i=0;i<inOrder.size();i++){
            s.push(inOrder[i]);
            while(!s.empty()&&s.top()==sequence[j]){
                s.pop();
                j++;
            }
        }
     s.empty();
 } };

使用递归的方式求解:

public class Solution {
    public boolean VerifySquenceOfBST(int [] sequence) {
        if(sequence.length==0) return false;
       
        return verifyPostorder(sequence,0,sequence.length-1);
    }
    public boolean verifyPostorder(int [] sequence,int start,int end){
        if(end - start <= 0) return true;
        int num = sequence[end];
        int index = start;
        while(sequence[index]<num&&index<=end-1) index++;
        int split = index;
        
        while(sequence[index]>num&&index<=end-1) index++;
        if(index != end)
            return false;
        return verifyPostorder(sequence,start,split-1)&&verifyPostorder(sequence,split,end-1);
    }
}
原文地址:https://www.cnblogs.com/ttzz/p/13828765.html