题目描述:
解题思路:
后序遍历有个特点,就是根节点是后序遍历数组的最后一个元素。从前根节点往前,最后一个大于它的元素往后的,都是右子树的节点,而它前面的则是左子树的节点。在例子中,5是根节点,5的前面最后一个比它大的是6,所以5的右子树节点只有6,1、3、2则是5的左子树节点。然后每一个的左子树和右子树又可以拆分左右子树。当左边界大于等于右边界的时候,节点只剩下一个或者没有了,证明树已经遍历完了。
代码实现:
class Solution {
public boolean verifyPostorder(int[] postorder) {
return helpertree(postorder,0,postorder.length-1);
}
boolean helpertree(int[] postorder,int left,int right){
if(left>=right) return true;
int l=left;
int root=postorder[right];
//判断第一个大于根的元素位置
while(postorder[l]<root){
l++;
}
int temp=l;
//判断是否右子树节点都大于根
for(int i=l;i<=right-1;i++){
if(postorder[i]<root) return false;
}
return helpertree(postorder,left,temp-1)&&helpertree(postorder,temp,right-1);
}
}
执行结果: