输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
参考以下这颗二叉搜索树:
5
/ \
2 6
/ \
1 3
示例 1:
输入: [1,6,3,2,5]
输出: false
示例 2:
输入: [1,3,2,6,5]
输出: true
提示:
数组长度 <= 1000
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
左子树<root, 右子树>root
class Solution {
public:
bool verifyPostorder(vector<int>& postorder) {
if(postorder.size() <= 2)
return true;
return check(postorder,0,postorder.size()-1);
}
bool check(vector<int>& order, int L, int R)
{
if(L >= R)//区间只有1个或者没有元素了
return true;
int root = order[R];//根
int i = L, j = R-1;//左子树的区间指针i,右子树j
while(i < R && order[i] < root)
i++;
while(j >= L && order[j] > root)
j--;
if(i-j != 1)//最终j应该紧贴i的左侧
return false;
return check(order,L,i-1) && check(order,j+1,R-1);
//递归查找2侧子树
}
};