注意:该题利用搜索树和后续遍历的特性
所以我们找到该树的所有根节点,判断是否符合左小,右大即可
class Solution {
public boolean verifyPostorder(int[] postorder) {
return verify(postorder, 0, postorder.length);
}
public boolean verify(int[] postorder,int left,int right) {//左闭右开
int len = right - left;
if (len <= 1) {
return true;
}
int root = postorder[right - 1];//找到根节点值
int i = left;
while (i < right) {//左边小 右边大 找到数组的切分点
if (postorder[i] > root) {
break;
}
++i;
}
if(i==right) {return verify(postorder,left,i-1);}//root是最大值时没有右子树 去判断左子树是否符合
for (int j = i; j < right-1; j++) {//判断是否符合右边大的特性
if (postorder[j] <= root) {
return false;
}
}
//root节点ok。判断root的左右子节点
if( verify(postorder,left,i)&& verify(postorder,i,right-1)){
return true;
}
return false;
}
}
评论