题目
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
示例
思路分析
代码实现
class Solution {
public boolean verifyPostorder(int[] postorder) {
int size = postorder.length;
boolean res = buildTree(postorder, 0, size - 1);
return res;
}
/**
* 思路分析
* step1:采用递归,一个n表示,遍历到了数组的哪一位,每一次遍历一位
* step2: 判断该位作为什么节点
*
* left和right表示该数组的左右边界
* @return
*/
public boolean buildTree(int[] postorder,int left,int right){
if(left >= right){
return true;
}
int root = postorder[right];
int rightIndex = right;
while (rightIndex >= left){
int num = postorder[rightIndex];
if (num >= root){
rightIndex--;
}else {
break;
}
}
//这时候right指向left树枝最右边idx
int leftPartIndex = rightIndex;
while(leftPartIndex>=left){
if(postorder[leftPartIndex] < root){
leftPartIndex--;
}else{
return false;
}
}
//右树进行比较
boolean resPart1 = buildTree(postorder, rightIndex + 1, right - 1);
boolean resPart2 = buildTree(postorder, leftPartIndex + 1, rightIndex);
return resPart1&&resPart2;
}
}