Post-order traversal sequence of binary search tree (look back)

Input an integer array to 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.

public class Solution {
    public boolean _VerifySquenceOfBST(int [] sequence,int start,int end){
        if(start >= end)
            return true;
        int root = sequence[end];
        int i = start;
        while(i < end){
            if(sequence[i] > root)
                break;
            i++;
        }
        int j = i;
        while(j < end){
            if(sequence[j] < root)
                return false;
            j++;
        }

        return _VerifySquenceOfBST(sequence,start,i-1) && _VerifySquenceOfBST(sequence,i,end-1);       
    }
    public boolean VerifySquenceOfBST(int [] sequence) {
        if(sequence.length == 0)
            return false;
        return _VerifySquenceOfBST(sequence,0,sequence.length-1);
    }
}

There is still a question, why is the final end condition start == end not enough? When the case is {4,6,7,5}, you can see:
(At this time start is 0, end is 3)
At the beginning, the value at i is 1, and the 4 on the left is start is 0, i-1 is 0, the start and end of the next recursion are the same, true!
On the right, start is 1, end-1 is 2, which is the {6,7} element. The next round of recursion is:
——7 is the root, and the value of i points to 7,
————so the left is 6, start and i-1 both point to 6, return true.
——The right i points to 7, and end-1 points to 6. At this time, end > start!

I can't use four subscripts to mark the start and end of the two arrays. It should be the same!

The key point is: don't forget the role of i. When considering or testing, you can't only think about the start and end at the beginning of the function, but also the two values ​​at the call site. The key is the value of i, because it is Affects these two values!

Reference:
https://blog.csdn.net/u013238950/article/details/50827977

Guess you like

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