题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
思路:
递归
注意点:
- while可以保证i加一次
- for循环保证精确break
- 但是在这个题目,应该要保证加一次for(int i=left;i<=right;i++)//这里应该是<=right,见上文注意点
eg: 4675
0,3-------------0,0-----------------1,2(这里midd不会变,其实是左子树,右子树没字符)以为是右子树,然后导致return fasle - if(left>=right) return true;//这里必须>=比如2,3,右子树左右系数为1,0
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
int len=sequence.size();
if(len==0) return false;
if(len==1) return true;
return VerifyCore(sequence,0,len-1);
}
bool VerifyCore(vector<int>& sequence,int left,int right)
{
int midd=left;
if(left>=right) return true;//这里必须>=比如2,3,右子树左右系数为1,0
for(int i=left;i<=right;i++)//这里应该是<=right,见上文注意点
{
if(sequence[i]>=sequence[right])
{
midd=i;
break;
}
}
for(int i=midd;i<=right;i++)
if(sequence[i]<sequence[right])
return false;
return VerifyCore(sequence,left,midd-1)&&VerifyCore(sequence,midd,right-1);
}
};
JAVA解法
class Solution {
public boolean verifyPostorder(int[] postorder) {
if (postorder.length == 0) {
return true;
}
List<Integer> postorderList = new ArrayList<>();
for (int i = 0; i < postorder.length; i++) {
postorderList.add(postorder[i]);
}
return doVerify(postorderList);
}
private boolean doVerify(List<Integer> postorderList) {
if (postorderList.size() == 0 || postorderList.size() == 1) {
return true;
}
int middle = postorderList.get(postorderList.size() - 1);
int i = 0;
while (i < postorderList.size()) {
if (postorderList.get(i) >= middle) {
break;
}
i++;
}
List<Integer> left = postorderList.subList(0, i - 1 > 0 ? i - 1 : 0);
List<Integer> right = postorderList.subList(i, postorderList.size() - 1);
for (int j = 0; j < right.size(); j++) {
if (right.get(j) < middle) {
return false;
}
}
return doVerify(left) && doVerify(right);
}
}