/* 题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。假设输入的数组的任意两个数字都互不相同。
*/
public boolean isPostOrder(int[] sequence)
{
if (sequence == null || sequence.length == 0)
{
return false;
}
return verify(sequence,0,sequence.length - 1);
}
private boolean verify(int[] sequence, int l, int r)
{
int rootValue = sequence[r];
//序列中只剩下两个节点或者更少的话,就不用了比较了. 2个结点的情况[x,根节点] 这样无论如何都符合条件.无法看x是左节点还是右节点.都可以
//一个节点的话不用说了.就一个根节点. 直接返回true.
if (r - l <= 1)
return true;
int cutIndex = l;
//找出分界点.因为后序遍历 的左节点都在前边,右节点都在右边.
while (cutIndex < r && sequence[cutIndex] <= rootValue)
cutIndex++;
//遍历右边的节点,左边的都是小于根节点的.所以只要判断右节点是不是都大于根节点就行了.
for (int i = cutIndex; i < r; i++)
if (sequence[i] < rootValue)
return false;
//递归遍历左右子树.
return verify(sequence, l, cutIndex - 1) && verify(sequence, cutIndex, r - 1);
}
《剑指offer》NO33 二叉搜索树的后序遍历序列 详解 <Java实现>
最新推荐文章于 2022-11-14 18:25:48 发布