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

简介: 剑指 Offer 33:二叉搜索树的后序遍历序列

题目

题目链接

输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。

参考以下这颗二叉搜索树:

5
    / \
   2   6
  / \
 1   3

示例 1:

输入: [1,6,3,2,5]
输出: false

示例 2:

输入: [1,3,2,6,5]
输出: true

解题

方法一:递归分治

参考链接

class Solution {
public:
    vector<int> postorder;
    bool isTree(int left,int right){
        if(left>=right) return true;
        int p=left;
        while(postorder[p]<postorder[right]) p++;
        int mid=p;
        while(postorder[p]>postorder[right]) p++;
        return p==right&&isTree(left,mid-1)&&isTree(mid,right-1);
    }
    bool verifyPostorder(vector<int>& postorder) {
        this->postorder=postorder;
        return isTree(0,postorder.size()-1);
    }
};

方法二:辅助单调栈

参考链接

class Solution {
public:
    bool verifyPostorder(vector<int>& postorder) {
        stack<int> st;
        int root=INT_MAX;
        for(int i=postorder.size()-1;i>=0;i--){
            if(postorder[i]>root) return false;
            while(!st.empty()&&postorder[i]<st.top()){
                root=st.top();
                st.pop();
            }
            st.push(postorder[i]);
        }
        return true;
    }
};
相关文章
|
5月前
剑指 Offer 54:二叉搜索树的第k大节点
剑指 Offer 54:二叉搜索树的第k大节点
50 0
|
5月前
|
存储
【LeetCode】剑指 Offer 54. 二叉搜索树的第k大节点
【LeetCode】剑指 Offer 54. 二叉搜索树的第k大节点
43 1
|
5月前
剑指 Offer 68 - I:二叉搜索树的最近公共祖先
剑指 Offer 68 - I:二叉搜索树的最近公共祖先
443 0
|
5月前
剑指 Offer 68 - II:二叉树的最近公共祖先
剑指 Offer 68 - II:二叉树的最近公共祖先
35 0
【剑指offer】-二叉搜索树的后序遍历序列-23/67
【剑指offer】-二叉搜索树的后序遍历序列-23/67
图解LeetCode——剑指 Offer 68 - II. 二叉树的最近公共祖先
图解LeetCode——剑指 Offer 68 - II. 二叉树的最近公共祖先
4688 1
剑指offer 34. 二叉搜索树的后序遍历序列
剑指offer 34. 二叉搜索树的后序遍历序列
51 0
剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
61 1
剑指 Offer 68 - I. 二叉搜索树的最近公共祖先