Sword Finger Offer 33. Post-order traversal sequence of binary search tree---recursion

Sword Finger Offer 33. Post-order traversal sequence of binary search tree

Post-order traversal of the array: left subtree--right subtree--root node

Take the root node, traverse the array segment from left to right, and divide the array segment with the index (k) of the first element greater than the root node

False if there are elements smaller than the root node in the right subtree

class Solution {
    public boolean verifyPostorder(int[] postorder) {
        if(postorder==null || postorder.length==0)  return true;
        return function(postorder,0,postorder.length-1);
    }
    private boolean function(int[] arr,int i,int j){
        if(i>j) return true;
        int root=arr[j];
        int k=i;//k为大于根节点的第一个节点的下标
        for(;k<j;k++){
            if(arr[k]>root) break;
        }
        for(int a=k;a<j;a++){
            if(arr[a]<root) return false;
        }
        boolean m=true,n=true;
        if(k>i) m=function(arr,i,k-1);
        if(k<j-1) n=function(arr,k,j-1);
        return m&&n;
    }
}

 

Guess you like

Origin blog.csdn.net/qq_41041762/article/details/108083861