Postorder traversal sequence of binary search tree

Question: Input an array of integers and determine whether the array is the result of a post-order traversal of a binary search tree. If yes, output Yes, otherwise output No. Suppose any two numbers of the input array are different from each other.

The idea is quite clear, but I don't know why, after submitting it several times, I can only pass some of the use cases, and only after the revision is passed. I always feel like I'm doing this wrong.

First, the last element of the post-order traversal is the root node root of the tree, and then the entire sequence can be divided into two parts, the left subtree and the right subtree of the root. All elements of the left subtree are smaller than the root, and the right subtree All elements of the subtree are larger than the root. According to this idea, you can use the left and right subtrees to recurse separately, and finally judge whether the conditions are met.

code show as below:

public boolean VerifySquenceOfBST(int [] sequence) {
        int leftRoot = 0, rightRoot = sequence.length-1;

        if (sequence.length == 0) return false;

        if (sequence.length <= 3) return true; //There is only one post-sequence sequence, and only true can be returned when there are only three nodes

        for (int i=0; i<sequence.length; i++) { //Find the position of the first element larger than root, and determine the range of the left subtree
            if (sequence[i] >= sequence[sequence.length-1]) {
                leftRoot = i;
                break;
            }
        }

        for (int i=leftRoot+1; i<sequence.length; i++) { //Determine whether all elements of the right subtree are larger than root
            if (sequence[i] < sequence[sequence.length-1]) return false;
        }

        if (leftRoot >= rightRoot)
            return VerifySquenceOfBST(Arrays.copyOfRange(sequence, 0, leftRoot));
        if (leftRoot == 0)
            return VerifySquenceOfBST(Arrays.copyOfRange(sequence, leftRoot, rightRoot));

       return VerifySquenceOfBST(Arrays.copyOfRange(sequence, 0, leftRoot))
               && VerifySquenceOfBST(Arrays.copyOfRange(sequence, leftRoot, rightRoot));
 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324613946&siteId=291194637