《剑指offer》面试题33. 二叉搜索树的后序遍历序列

时间:2022-04-17 08:00:19

问题描述

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

 

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

     5
/ \
2 6
/ \
1 3
示例 1: 输入: [1,6,3,2,5]
输出: false
示例 2: 输入: [1,3,2,6,5]
输出: true
  提示: 数组长度 <= 1000

代码(递归)

class Solution {
public:
bool verifyPostorder(vector<int>& postorder) {
return fun(postorder,0,postorder.size()-1);
}
bool fun(vector<int>& postorder,int left,int right)
{
if(left >= right)return true;
int m = left;
//postorder[right]为根结点的值,寻找左子树
while(postorder[m] < postorder[right])m++;
//判断右子树中的值是否符合二叉树定义
for(int i = m; i < right; ++i)
if(postorder[i] < postorder[right])
return false;
return fun(postorder,left,m-1) && fun(postorder,m,right-1);
}
};

结果:

执行用时 :0 ms, 在所有 C++ 提交中击败了100.00%的用户
内存消耗 :6.8 MB, 在所有 C++ 提交中击败了100.00%的用户

代码(单调栈)

public:
bool verifyPostorder(vector<int>& postorder) {
int i, n = postorder.size();
stack<int> st;
int root = INT_MAX;
for(i = n-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;
}
};

结果:

执行用时 :4 ms, 在所有 C++ 提交中击败了66.61%的用户
内存消耗 :7.1 MB, 在所有 C++ 提交中击败了100.00%的用户