输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
参考以下这颗二叉搜索树:
5
/ \
2 6
/ \
1 3
示例 1:
输入: [1,6,3,2,5]
输出: false
示例 2:
输入: [1,3,2,6,5]
输出: true
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof
此题比较简单的解法就是利用分治递归的方法,按照left -->right--->root, 则有root >left 并且root < right
class Solution {
public:
bool vertifySubTree(vector<int>& postorder, int l, int r) {
if (l >= r)
return true;
int i ;
for (i = r; i >= l; --i) {
if (postorder[i] < postorder[r]) {
break;
}
}
for (int j = i; j >= l; --j) {
if (postorder[j] > postorder[r])
return false;
}
return vertifySubTree(postorder, l, i) && vertifySubTree(postorder, i + 1, r - 1);
}
bool verifyPostorder(vector<int>& postorder) {
return vertifySubTree(postorder, 0, postorder.size()-1);
}
};
比较不容易想到的解法就是单调辅助栈的方法,详细的可以参考
二叉搜索树的后序遍历序列(辅助栈 最清晰易懂的可视化讲解)_ZBH4444的博客-优快云博客
C++ 实现
class Solution {
public:
bool verifyPostorder(vector<int>& postorder) {
stack<int> stk;
int root = INT_MAX;
for(int i = postorder.size() - 1 ; i >= 0 ; i--)
{
if(postorder[i] > root)
return false;
//递减
while(!stk.empty() && stk.top() > postorder[i])
{
root = stk.top();
stk.pop();
}
//递增
stk.push(postorder[i]);
}
return true;
}
};